コード例 #1
0
ファイル: test_views.py プロジェクト: aberrier/exploud
def test_converse_nlp_services_offline(mock_check_special_intent, client,
                                       converse_text_request):
    mock_check_special_intent.side_effect = ExternalAPIException()
    res = client.post(url_for('converse.conversation-text'),
                      content_type='application/json',
                      data=json.dumps(converse_text_request))
    expected_result = {'errors': [dict(ExternalAPIException())]}
    assert res.status_code == 503
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_check_special_intent.call_count == 1
コード例 #2
0
ファイル: test_views.py プロジェクト: aberrier/exploud
def test_speak_ibm_not_working(mock_ibm_send_request, client, ibm_request):
    mock_ibm_send_request.side_effect = ExternalAPIException(api_name='IBM')
    res = client.post(url_for('tts_ibm.speak'),
                      content_type='application/json',
                      data=json.dumps({
                          'language': ibm_request['language'],
                          'text': ibm_request['text']
                      }))

    expected_result = {'errors': [dict(ExternalAPIException(api_name='IBM'))]}

    assert mock_ibm_send_request.call_count == 1
    assert res.status_code == 503
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
コード例 #3
0
def forecast_get_weather(lat, long, time, language):
    params = {'lang': language, 'units': 'auto'}
    res = requests.get('https://api.darksky.net/forecast/' + token + '/' +
                       str(lat) + ',' + str(long) + ',' + str(time),
                       params=params)
    print(res.content)
    if res.status_code == 200:
        return res.json()
    elif res.status_code == 400:
        raise ExternalAPIException(api_name='Dark Sky', description=res.json())
    elif res.status_code == 401:
        raise InvalidCredentialsException('Dark Sky')
    else:
        raise ExternalAPIException(api_name='Dark Sky',
                                   description='http_code:{}'.format(
                                       res.status_code))
コード例 #4
0
ファイル: test_views.py プロジェクト: aberrier/exploud
def test_intent_recast_not_working(mock_recast_send_request_intent, client,
                                   recast_intent_request,
                                   recast_intent_response):
    mock_recast_send_request_intent.side_effect = ExternalAPIException()
    res = client.post(url_for('nlp_recast.intent'),
                      content_type='application/json',
                      data=json.dumps({
                          'text':
                          recast_intent_request['text'],
                          'language':
                          recast_intent_request['language']
                      }))
    expected_result = {'errors': [dict(ExternalAPIException())]}
    assert mock_recast_send_request_intent.call_count == 1
    assert res.status_code == 503
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
コード例 #5
0
ファイル: helpers.py プロジェクト: aberrier/exploud
def get_news():
    res = requests.get(url=services_url + '/api/news', headers=headers)
    if res.status_code == 200:
        return res.json()
    else:
        raise ExternalAPIException(
            api_name='API Services - Cryptonews',
            description='HTTP code: {}\nDetails: {}'.format(
                res.status_code, res.content))
コード例 #6
0
ファイル: test_views.py プロジェクト: aberrier/exploud
def test_memory_recast_not_working(mock_recast_send_request_memory, client,
                                   recast_memory_request,
                                   recast_memory_response):
    mock_recast_send_request_memory.side_effect = ExternalAPIException()
    res = client.post(url_for('nlp_recast.memory'),
                      content_type='application/json',
                      data=json.dumps({
                          'field':
                          recast_memory_request['field'],
                          'value':
                          recast_memory_request['value'],
                          'user_id':
                          recast_memory_request['user_id'],
                      }))
    expected_result = {'errors': [dict(ExternalAPIException())]}
    assert res.status_code == 503
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_memory.call_count == 1
コード例 #7
0
def test_exception_external_api_exception():
    expected_result = {
        'code': 'external_api_error',
        'msg': 'test API is not working properly.'
    }

    with pytest.raises(ExternalAPIException) as e:
        raise ExternalAPIException(api_name='test API')
    e = e.value

    assert e.status_code == 503
    assert sorted(e.to_dict().items()) == sorted(expected_result.items())
コード例 #8
0
def coinmarketcap_get_currency(currency, device='EUR'):
    print(currency)
    res = requests.get('https://api.coinmarketcap.com/v1/ticker/' + currency +
                       '/?convert=EUR',
                       params={'convert': device})
    if res.status_code == 200:
        return res.json()
    elif res.status_code == 404:
        raise ResourceNotFoundException(currency)
    else:
        raise ExternalAPIException(api_name='CoinMarketCap',
                                   description='http_code:{}'.format(
                                       res.status_code))
コード例 #9
0
def google_news_get_news(source='google-news-fr'):
    res = requests.get('https://newsapi.org/v2/top-headlines',
                       params={
                           'sources': source,
                           'apiKey': token
                       })
    print(res.content)
    if res.status_code == 200:
        return res.json()
    elif res.status_code == 400:
        raise BadParameterException(source)
    else:
        raise ExternalAPIException(api_name='Google News',
                                   description='http_code:{}'.format(
                                       res.status_code))
コード例 #10
0
def ibm_send_request(text, language):
    url = IBM_CREDENTIALS['url'] + '/v1/synthesize?voice={}'.format(
        LANG_MAP.get(language, DEFAULT_LANGUAGE))
    data = json.dumps({'text': text})
    headers = {'Content-Type': 'application/json', 'Accept': 'audio/wav'}
    auth = (IBM_CREDENTIALS['username'], IBM_CREDENTIALS['password'])

    res = requests.post(url=url, data=data, headers=headers, auth=auth)

    if res.status_code == 200:
        return res.content
    elif res.status_code == 401:
        raise InvalidCredentialsException(api_name='IBM')
    else:
        raise ExternalAPIException(api_name='IBM')
コード例 #11
0
ファイル: helpers.py プロジェクト: aberrier/exploud
def get_weather(latitude, longitude, time, language):
    data = {
        'latitude': latitude,
        'longitude': longitude,
        'time': time,
        'language': language
    }
    data = json.dumps(data)
    res = requests.post(url=services_url + '/api/weather/',
                        data=data,
                        headers=headers)
    if res.status_code == 200:
        return res.json()
    else:
        raise ExternalAPIException(
            api_name='API Services - Weather',
            description='HTTP code: {}\nDetails: {}'.format(
                res.status_code, res.content))
コード例 #12
0
ファイル: test_views.py プロジェクト: aberrier/exploud
def test_converse_stt_stop(mock_google_speech_send_request,
                           mock_recast_send_request_dialog, client,
                           converse_audio_request):
    mock_google_speech_send_request.side_effect = Exception()
    res = client.post(url_for('converse.conversation-text'),
                      content_type='multipart/form-data',
                      data={
                          'audio':
                          (io.BytesIO(converse_audio_request['audio']),
                           'audio.wav'),
                          'language':
                          converse_audio_request['language'],
                          'user_id':
                          converse_audio_request['user_id']
                      })
    expected_result = {'errors': [dict(ExternalAPIException('Google'))]}

    assert res.status_code == 503
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_dialog.call_count == 0
コード例 #13
0
def microsoft_analyse_picture(file):
    url = MICROSOFT_API_URL + '/detect?returnFaceId=true&returnFaceAttributes=emotion'
    params = {'returnFaceId': True, 'returnFaceAttributes': ['emotion']}

    headers = {
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key': MICROSOFT_API_KEY
    }

    res = requests.post(url=url, data=file, headers=headers, params=params)

    if res.status_code == 200:
        data = res.json()
        try:
            emotions = data[0]['faceAttributes']['emotion']
        except (KeyError, IndexError):
            return {'emotion': None}

        if not emotions:
            return {'emotion': None}

        emo = ''
        max_percent = 0
        for key, percent in emotions.items():
            if percent > max_percent:
                emo = key
                max_percent = percent

        return {'emotion': emo, 'percent': max_percent}
    elif res.status_code == 401:
        raise InvalidCredentialsException(api_name='Microsoft')
    elif res.status_code == 429:
        raise APIThrottlingException(api_name='Microsoft')
    else:
        print(res.status_code)
        raise ExternalAPIException(api_name=res.status_code)
コード例 #14
0
ファイル: views.py プロジェクト: aberrier/exploud
def conversation(want):
    output = {}
    skipping_nlp = False
    user_id = None
    message = None
    intent = None
    text = None
    language = None
    input_type, errors, code = check_request(request)
    if errors:
        return jsonify({'errors': errors}), code
    # Case: input is audio
    if input_type == 'audio':
        if 'user_id' in request.form:
            user_id = request.form['user_id']
        audio = request.files['audio']
        language = request.form['language']
        if language not in LANGUAGES_CODE:
            return jsonify({'errors': [dict(BadParameterException('language', valid_values=LANGUAGES_CODE))]}), BadParameterException.status_code
        try:
            file_content = audio.read()
        except Exception:
            return jsonify({'errors': [dict(BadParameterException('audio'))]}), BadParameterException.status_code

        try:
            res = stt.google_speech_send_request(file_content, language)
            text = res["text"]
            stt_confidence = res["confidence"]

            output['input'] = text
            output['stt_confidence'] = stt_confidence
        except OperationFailedException as e:
            logger.error(e)
            message = CUSTOM_MESSAGES[SIMPLIFIED_LANGUAGES_CODE[language]]["not-heard"]
            intent = DEFAULT_INTENT
            skipping_nlp = True
        except Exception as e:
            logger.error(e)
            return jsonify({'errors': [dict(ExternalAPIException('Google'))]}), ExternalAPIException.status_code
    # Case: input is text
    elif input_type == 'text':
        user_id = request.json.get('user_id')
        # print(user_id)
        text = request.json['text']
        language = request.json['language']

        output['input'] = text
        if language not in LANGUAGES_CODE:
            return jsonify({'errors': [dict(BadParameterException('language', valid_values=LANGUAGES_CODE))]}), BadParameterException.status_code
    if not skipping_nlp:
        # Analyze the text
        try:
            res_nlp = nlp.recast_send_request_dialog(text, user_id, SIMPLIFIED_LANGUAGES_CODE[language])
            output['nlp'] = res_nlp
            print(res_nlp)
            if not res_nlp['results']['nlp']['intents']:
                intent = DEFAULT_INTENT
            else:
                intent = res_nlp['results']['nlp']['intents'][0]['slug']
            if not res_nlp['results']['messages']:
                message = CUSTOM_MESSAGES[SIMPLIFIED_LANGUAGES_CODE[language]]["not-understand"]
            else:
                message = res_nlp['results']['messages'][0]['content']

        except (InvalidCredentialsException, ExternalAPIException) as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({'errors': [dict(APIException(code='nlp_error', msg=str(e)))]}), APIException.status_code
        # Check special intents
        try:
            spec_message = check_special_intent(intent, res_nlp['results'], SIMPLIFIED_LANGUAGES_CODE[language])
            if spec_message:
                message = spec_message
        except ExternalAPIException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({'errors': [dict(APIException(code='services_error', msg=str(e)))]}), APIException.status_code
    # Regroup information
    output['message'] = message
    output['intent'] = intent
    # Send the result
    if want == 'text':
        return jsonify(output), 200
    elif want == 'audio':
        try:
            res_tts = tts.ibm_send_request(message, language)
        except (InvalidCredentialsException, ExternalAPIException) as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            api_e = APIException(code='tts_error', msg=str(e))
            return jsonify({'errors': [dict(api_e)]}), api_e.status_code

        response = Response(res_tts, mimetype="audio/wav", status=200)
        response.headers['JSON'] = json.dumps(output)
        return response
    else:
        # Impossible !
        return jsonify({'errors': [dict(APIException(code='invalid_output_format_requested'))]}), APIException.status_code