示例#1
0
文件: views.py 项目: aberrier/exploud
def check_request(req):
    errors = []
    content_type = req.headers.get('Content-Type')
    if not content_type:
        return 'none', [dict(MissingHeaderException('Content-Type'))], MissingHeaderException.status_code

    # Case: input is audio
    if content_type.startswith(tuple(AUDIO_FORMATS)):
        if 'audio' not in req.files:
            errors.append(dict(MissingParameterException('audio')))
        if 'language' not in req.form:
            errors.append(dict(MissingParameterException('language')))
        return 'audio', errors, MissingParameterException.status_code if errors else 200

    # Case: input is text
    elif content_type.startswith(tuple(TEXT_FORMATS)):
        if 'text' not in req.json:
            errors.append(dict(MissingParameterException('text')))

        if 'language' not in req.json:
            errors.append(dict(MissingParameterException('language')))
        return 'text', errors, MissingParameterException.status_code if errors else 200
    else:
        errors.append(dict(BadHeaderException('Content-Type', valid_values=SUPPORTED_FORMATS)))
        return 'none', errors, BadHeaderException.status_code
示例#2
0
def speak():
    errors = []

    if 'text' not in request.json:
        errors.append(dict(MissingParameterException('text')))

    if 'language' not in request.json:
        errors.append(dict(MissingParameterException('language')))

    if errors:
        return jsonify({'errors': errors}), 400

    text = request.json['text']
    language = request.json['language']

    if language not in LANGUAGES_CODE:
        return jsonify({'errors': [dict(BadParameterException('language', valid_values=LANGUAGES_CODE))]}), 400

    try:
        res = ibm_send_request(text, language)
    except (InvalidCredentialsException, ExternalAPIException) as e:
        return jsonify({'errors': [dict(e)]}), e.status_code
    except Exception as e:
        logger.error(e)
        api_e = APIException()
        return jsonify({'errors': [dict(api_e)]}), api_e.status_code

    return Response(res, mimetype="audio/wav", status=200)
示例#3
0
文件: views.py 项目: aberrier/exploud
def recognize():
    errors = []
    if 'audio' not in request.files:
        errors.append(dict(MissingParameterException('audio')))
    if 'language' not in request.form:
        errors.append(dict(MissingParameterException('language')))

    if errors:
        return jsonify({'errors': errors}), 400

    file = request.files['audio']
    file_content = file.read()
    language = request.form['language']
    if language not in LANGUAGES_CODE:
        return jsonify({
            'errors': [
                dict(
                    BadParameterException('language',
                                          valid_values=LANGUAGES_CODE))
            ]
        }), 400

    try:
        res = google_speech_send_request(file_content, language)
    except (OperationFailedException, BadParameterException) as e:
        logger.error(e)
        return jsonify({'errors': [dict(e)]}), e.status_code

    return jsonify(res), 200
示例#4
0
文件: views.py 项目: aberrier/exploud
def answer():
    errors = []
    if request.json:
        if 'text' not in request.json:
            errors.append(dict(MissingParameterException('text')))

        if 'language' not in request.json:
            errors.append(dict(MissingParameterException('language')))
        if errors:
            return jsonify({'errors': errors}), 400
        text = request.json['text']
        language = request.json['language']
        if language not in LANGUAGES_CODE:
            return jsonify({
                'errors': [
                    dict(
                        BadParameterException('language',
                                              valid_values=LANGUAGES_CODE))
                ]
            }), 400
        try:
            res = recast_send_request_dialog(text, request.json.get('user_id'))
            return jsonify(res['results']), 200
        except InvalidCredentialsException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except ExternalAPIException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({'errors': [dict(APIException('nlp_answer'))]}), 500

    else:
        errors.append(dict(APIException('no_content')))
        return jsonify({'errors': errors}), 400
示例#5
0
def weather():
    errors = []

    if request.json:
        if 'latitude' not in request.json:
            errors.append(dict(MissingParameterException('latitude')))

        if 'longitude' not in request.json:
            errors.append(dict(MissingParameterException('longitude')))

        if 'time' not in request.json:
            errors.append(dict(MissingParameterException('time')))

        if 'language' not in request.json:
            errors.append(dict(MissingParameterException('language')))

        if errors:
            return jsonify({'errors': errors}), 400

        latitude = request.json['latitude']
        longitude = request.json['longitude']
        time = request.json['time']
        language = request.json['language']
        try:
            res = forecast_get_weather(latitude, longitude, time, language)
            output = {
                "currently": res["currently"],
                "daily": res["daily"]["data"][0],
                "timezone": res["timezone"]
            }
            return jsonify(output), 200
        except InvalidCredentialsException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except ExternalAPIException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({
                'errors': [
                    dict(
                        APIException('weather_parse({})'.format(
                            type(e).__name__)))
                ]
            }), 500

    else:
        errors.append(dict(APIException('no_content')))
        return jsonify({'errors': errors}), 400
示例#6
0
def test_speak_missing_text_and_language(mock_ibm_send_request, client):
    res = client.post(url_for('tts_ibm.speak'),
                      content_type='application/json',
                      data=json.dumps({}))

    expected_result = {
        'errors': [
            dict(MissingParameterException('text')),
            dict(MissingParameterException('language'))
        ]
    }

    assert mock_ibm_send_request.call_count == 0
    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
示例#7
0
def test_converse_missing_language(mock_recast_send_request_dialog, client,
                                   converse_text_request,
                                   converse_audio_request):
    res = client.post(url_for('converse.conversation-text'),
                      content_type='application/json',
                      data=json.dumps({
                          'text':
                          converse_text_request['text'],
                          'user_id':
                          converse_text_request['user_id']
                      }))
    expected_result = {'errors': [dict(MissingParameterException('language'))]}

    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())

    res = client.post(url_for('converse.conversation-audio'),
                      content_type='multipart/form-data',
                      data={
                          'audio':
                          (io.BytesIO(converse_audio_request['audio']),
                           'audio.wav'),
                          'user_id':
                          converse_audio_request['user_id']
                      })
    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_dialog.call_count == 0
示例#8
0
def test_answer_missing_audio_file_and_language(
        mock_recast_send_request_dialog, client):
    res = client.post(url_for('nlp_recast.answer'),
                      content_type='application/json',
                      data=json.dumps({"mock": "mock"}))

    expected_result = {
        'errors': [
            dict(MissingParameterException('text')),
            dict(MissingParameterException('language'))
        ]
    }
    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_dialog.call_count == 0
示例#9
0
def test_recognize_missing_audio_file_and_language(mock_google_speech_send_request, client):
    res = client.post(
        url_for('stt_google.recognize'),
        content_type='multipart/form-data',
        data={}
    )

    expected_result = {
        'errors': [
            dict(MissingParameterException('audio')),
            dict(MissingParameterException('language'))
        ]
    }

    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(expected_result.items())
    assert mock_google_speech_send_request.call_count == 0
def test_exception_missing_parameter_exception():
    expected_result = {'code': 'missing_parameter', 'msg': 'test is missing.'}

    with pytest.raises(MissingParameterException) as e:
        raise MissingParameterException(parameter='test')
    e = e.value

    assert e.status_code == 400
    assert sorted(e.to_dict().items()) == sorted(expected_result.items())
示例#11
0
文件: views.py 项目: aberrier/exploud
def memory():
    errors = []
    if request.json:
        if 'field' not in request.json:
            errors.append(dict(MissingParameterException('field')))

        if 'user_id' not in request.json:
            errors.append(dict(MissingParameterException('user_id')))

        if errors:
            return jsonify({'errors': errors}), 400

        field = request.json['field']
        if field not in SUPPORTED_FIELDS:
            return jsonify({
                'errors': [
                    dict(
                        BadParameterException('field',
                                              valid_values=SUPPORTED_FIELDS))
                ]
            }), 400
        value = request.json.get('value')
        user_id = request.json['user_id']
        try:
            res = recast_send_request_memory(field, user_id, value)
            return jsonify(res['results']), 200
        except InvalidCredentialsException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except ExternalAPIException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({
                'errors':
                [dict(APIException('nlp_memory'.format(type(e).__name__, e)))]
            }), 500

    else:
        errors.append(dict(APIException('no_content')))
        return jsonify({'errors': errors}), 400
示例#12
0
def test_intent_missing_audio_file(mock_recast_send_request_intent, client,
                                   recast_intent_request,
                                   recast_intent_response):
    res = client.post(url_for('nlp_recast.intent'),
                      content_type='application/json',
                      data=json.dumps(
                          {'language': recast_intent_request['language']}))

    expected_result = {'errors': [dict(MissingParameterException('text'))]}
    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_intent.call_count == 0
示例#13
0
def test_converse_missing_audio(mock_recast_send_request_dialog, client,
                                converse_audio_request):
    res = client.post(url_for('converse.conversation-audio'),
                      content_type='multipart/form-data',
                      data={
                          'language': converse_audio_request['language'],
                          'user_id': converse_audio_request['user_id']
                      })
    expected_result = {'errors': [dict(MissingParameterException('audio'))]}

    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_dialog.call_count == 0
示例#14
0
def test_converse_missing_text(mock_recast_send_request_dialog, client,
                               converse_text_request):
    res = client.post(url_for('converse.conversation-text'),
                      content_type='application/json',
                      data=json.dumps({
                          'user_id':
                          converse_text_request['user_id'],
                          'language':
                          converse_text_request['language']
                      }))
    expected_result = {'errors': [dict(MissingParameterException('text'))]}

    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_dialog.call_count == 0
示例#15
0
def test_memory_missing_field(mock_recast_send_request_memory, client,
                              recast_memory_request, recast_memory_response):
    res = client.post(url_for('nlp_recast.memory'),
                      content_type='application/json',
                      data=json.dumps({
                          'value':
                          recast_memory_request['value'],
                          'user_id':
                          recast_memory_request['user_id'],
                      }))

    expected_result = {'errors': [dict(MissingParameterException('field'))]}
    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_memory.call_count == 0
示例#16
0
def test_answer_missing_language(mock_recast_send_request_dialog, client,
                                 recast_answer_request,
                                 recast_answer_response):
    res = client.post(url_for('nlp_recast.answer'),
                      content_type='application/json',
                      data=json.dumps({
                          'text':
                          recast_answer_request['text'],
                          'user_id':
                          recast_answer_request['conversation_id'],
                      }))

    expected_result = {'errors': [dict(MissingParameterException('language'))]}
    assert res.status_code == 400
    assert sorted(json.loads(res.data).items()) == sorted(
        expected_result.items())
    assert mock_recast_send_request_dialog.call_count == 0