コード例 #1
0
def check_request(request):
    """
        Validates that our request is well formatted

        Returns:
        - assertion value: True if request is ok, False otherwise
        - error message: empty if request is ok, False otherwise
    """
    if "observation_id" not in request.keys():
        error = "Field 'observation_id' missing from request: {}".format(request)
        return False, error
    elif 'data' not in request.keys():
        error = "Field `data` missing from request: {}".format(request)
        return False, error
    else:
        return True, ""
コード例 #2
0
def Predict():
    request = extract_message()
    logger.debug("Request: %s", request)
    features_dict = {}
    for k in request.keys():
        features_dict[k] = get_data_from_json(request[k])

    predictions = user_model.predict(features_dict)
    logger.debug("Predictions: %s", predictions)

    # If predictions is an numpy array or we used the default data then return as numpy array
    predictions = np.array(predictions)
    if len(predictions.shape) > 1:
        class_names = get_class_names(user_model, predictions.shape[1])
    else:
        class_names = []
    data = array_to_rest_datadef(predictions, class_names,
                                 request.get("data", {}))
    response = {"data": data, "meta": {}}

    tags = get_custom_tags(user_model)
    if tags:
        response["meta"]["tags"] = tags
    metrics = get_custom_metrics(user_model)
    if metrics:
        response["meta"]["metrics"] = metrics
    return jsonify(response)
コード例 #3
0
def validate_required_inputs(request):
    required = ['text', 'model_name']
    missing = missing = [
        field for field in required if field not in request.keys()
    ]
    if missing:
        err = {field: f"the {field} field is required" for field in missing}
        return err, 422
コード例 #4
0
    def populate_list(bucket):

        for entry in bucket["by_top_hit"]["hits"]["hits"]:
            count = len(request.keys())
            for key in request.keys():
                if (key == "report_date" and request[key] != "ALL KEYS"):
                    try:
                        days = compare_two_dates(entry['_source'][key][0:10],
                                                 request[key])
                    except:
                        try:
                            t_index = entry['_source'][key].index('T')
                            report_date = entry['_source'][key][0:t_index]
                            days = compare_two_dates(report_date, request[key])
                        except:
                            report_date = entry['_source']['time'][0:10]
                            days = compare_two_dates(report_date, request[key])

                    if (days >= 0 and days <= interval):
                        count -= 1
                    else:
                        break

                elif (request[key] == "ALL KEYS"):
                    count -= 1
                elif (entry['_source'].get(key) == None):
                    break
                elif (entry['_source'][key].lower() == request[key].lower()):
                    count -= 1
                elif (re.match(request[key].lower(),
                               entry['_source'][key].lower()) != None):
                    count -= 1

            if (count == 0 and visited.get(entry["_source"]["sr_id"]) == None
                    and entry["_index"] == "version_string_sda"):
                visited[entry["_source"]["sr_id"]] = True
                lst.append(entry["_source"])
コード例 #5
0
def parse_signed_request(request):
    if not isinstance(request, dict) or \
            set(request.keys()) != {'message', 'signature'} or \
            not isinstance(request['message'], dict) or \
            not isinstance(request['signature'], str):
        return None, 'Unexpected formatting'

    signature = request['signature']
    message_dict = request['message']
    message_str = json.dumps(message_dict,
                             separators=(',', ':'),
                             sort_keys=True).encode('ascii').decode()

    response = host.call('verifymessage', secAuthorizerAddress, signature,
                         message_str)
    if not response:
        return None, 'Invalid signature'

    return message_dict, ''
コード例 #6
0
def convert_input(request):
    """
    convert input given through form into a model readable form. can be done through calling preprocess after converting to something like a dataframe
    additional arguements for further customization?
    """
    keys = [str(k) for k in request.keys()]
    print(request)
    feature_names = [k.split('-')[0] for k in keys]
    print(feature_names)
    feature_order = [int(k.split('-')[1]) for k in keys]
    feature_values = [request[keys[i]] for i in range(len(feature_names))]
    
    print(feature_order)
    print(feature_values)
    print('------------------------------------------------------------------------------------------------------')
    print(request)

    

    df = pd.DataFrame(columns=feature_names)
    df.loc[0] = feature_values
    print(df.head())

    query = 'select file_name from preprocess where model_id = ?'
    cur = conn.execute(query,(str(keys[0]).split('-')[2],))
    file_name = cur.fetchone()

    
    spec = importlib.util.spec_from_file_location("module.name", 'preprocess/' + file_name[0])
    preprocess = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(preprocess)

    # preprocess = importlib.import_module('preprocess/' + file_name[0] + ".py")
    df = preprocess.preprocess(df)
    # df.to_csv("test.csv")
    return prediction(str(keys[0]).split('-')[2],df)
コード例 #7
0
def create():
    """
    This function creates a new pathogen_model in the pathogen_models structure
    based on the passed in pathogen_model data
    :return:        201 on success, 406 on pathogen_model exists
    """

    # if the item comes in as a single, let's [
    if type(request.form['name']) is str:
        new_model, schema = insert_one_model(form=request.form, files=request.files)
    else:
        for i in range(len(request.form['name'])):
            new_model, schema = insert_one_model(form={k: request.form[k][i] for k in request.keys()},
                                                          files={k: request.form[k][i] for k in request.files.keys()})
    db.session.commit()

    # Serialize and return the newly created pathogen_model in the response
    data = schema.dump(new_model).data

    return data, 201