Exemplo n.º 1
0
def classify():
    """
    Input base 64 encoded (x, y, 3) image data
    :return: classification label, prediction
    """
    global count
    count += 1
    try:
        input_data = request.json["data"]
        encoded_data = input_data[input_data.find(',') + 1:]
        decoded_data = base64.b64decode(encoded_data)

        with open('TESTME.jpg', 'wb') as wfile:
            wfile.write(decoded_data)

        img = mpimg.imread('TESTME.jpg')
        (labels, p) = get_prediction(img)
        predictions = p.tolist()
        classification_mela = "false"
        if predictions[1] >= 0.5:
            classification_mela = "true"
        data = {
            "labels": labels,
            "predictions": predictions,
            "melanocytic": classification_mela
        }
        return jsonify(data), 200
        #ret_str = "This image is predicted to be " + predictions*100.0 + "% malignant."
        #return ret_str, 200
    except Exception as e:  #generic error handling
        return str(e), 400
Exemplo n.º 2
0
def get_image_classification(image, model):
    #print headings
    print 'Image name\t0 - Plot\t1 - Table\t2 - Other\tClassification'

    #classify each image
    name, plot, table, other, classification = prediction.get_prediction(image, model, 0.6)
    print "%s\t%f\t%f\t%f\t%s" % (name, plot, table, other, classification)
Exemplo n.º 3
0
def predict():
    if 'structure' not in request.values:
        return fmt_msg('Invalid request')

    structure = request.values.get('structure')
    if not 0 < len(structure) < 32768:
        return fmt_msg('Request size is invalid')

    if not is_plain_text(structure):
        return fmt_msg('Request contains unsupported (non-latin) characters')

    fmt = detect_format(structure)

    if fmt == 'cif':
        ase_obj, error = cif_to_ase(structure)
        if error:
            return fmt_msg(error)

    elif fmt == 'poscar':
        ase_obj, error = poscar_to_ase(structure)
        if error:
            return fmt_msg(error)

    else:
        return fmt_msg('Provided data format is not supported')

    if 'disordered' in ase_obj.info:
        descriptor, error = get_ordered_descriptor(ase_obj)
        if error:
            return fmt_msg(error)

    else:
        ase_obj, error = refine(ase_obj)
        if error:
            return fmt_msg(error)

        descriptor, error = get_aligned_descriptor(ase_obj)
        if error:
            return fmt_msg(error)

    prediction, error = get_prediction(descriptor, active_ml_models)
    if error:
        return fmt_msg(error)

    if len(ase_obj) < 10:
        orig_cell = ase_obj.cell[:]
        ase_obj *= (2, 2, 2)
        ase_obj.set_cell(orig_cell)
    ase_obj.center(about=0.0)

    return Response(json.dumps(
        {
            'prediction': prediction,
            'legend': get_legend(prediction),
            'formula': html_formula(get_formula(ase_obj)),
            'p1_cif': ase_to_eq_cif(ase_obj)
        },
        indent=4,
        escape_forward_slashes=False),
                    content_type='application/json')
Exemplo n.º 4
0
def show_mask(data_index):
    img_path = "../pictures/pictures_detect_local_evaluate_100/{}.png".format(
        data_index)
    img = get_img(img_path)

    boxes, probs, classification_logits, regression_values = get_prediction(
        img)
    bounding_boxes = []
    for i in range(len(boxes)):
        if probs[i] > .9:
            x1, y1, x2, y2 = get_final_box(boxes[i],
                                           regression_values[i],
                                           limit_border=False)
            label = np.argmax(classification_logits[i])
            bounding_boxes.append({
                "x1": x1 * real_image_width // feature_size,
                "y1": y1 * real_image_height // feature_size,
                "x2": x2 * real_image_width // feature_size,
                "y2": y2 * real_image_height // feature_size,
                "label": label,
            })

    mask = get_prediction_mask(img)

    show(data_index, img_path, bounding_boxes, mask)
Exemplo n.º 5
0
def predict(audio_data):
    logger.info(audio_data)
    filename = secure_filename(audio_data.filename)
    path = f'./app/uploads/{filename}.wav'
    audio_data.save(path)

    name = prediction.get_prediction(path)
    return {'name': name}
Exemplo n.º 6
0
def get_image_classification(image, model):
    #print headings
    print 'Image name\t0 - Plot\t1 - Table\t2 - Other\tClassification'

    #classify each image
    name, plot, table, other, classification = prediction.get_prediction(
        image, model, 0.6)
    print "%s\t%f\t%f\t%f\t%s" % (name, plot, table, other, classification)
def main(params):
    print("let`s get started!")
    print("trained models are detected!"
          ) if not params['model_train'] else print(
              "let`s train CTR, CPC and reach")
    print("predicted values are detected!"
          ) if not params['predict'] else print("let`s predict")

    # gather data from .csv.
    data = data_access.get_data_from_csv(params)
    # doing manipulations for parsing keywords and calculating total cost and revenue for each rows.
    data = data_manipulation.calculate_total_cost_revenue_conversion(data)
    # for sample data 8 million gathers combinations of each categorical features
    params['pred_data'], params[
        'dashboard_filters'], iters = prediction.combination_data_preparation(
            data, params)

    # start prediction or training model procces of each metric
    for y in params['output']:
        # if we assign model path is gathers model from there. Othervise path is assigned in constans.
        _path = params['output'][y]['model_path'] if params['output'][y][
            'model_path'] is not None else constants.model_save_path
        if params['model_train']:
            # inputs for training process
            if params['output'][y]['model_features']['num'] is None:
                X_decoded = constants.model_features[y]
            else:
                X_decoded = params['output'][y]['model_features']
            # this is for one-hot encoding for categorical features.
            _data, X_encoded = data_manipulation.converting_numeric_encoder(
                data, X_decoded, y)
            # each learning process assign for GGM, DRF, DNN, GLM machine Learning models.
            # At the end H2o allows us to find the best model by using stack Ensemble model
            _model = model_train.best_prediction_model(
                _data, constants.search_criteria, constants.hyper_p_gbm,
                constants.hyper_p_drf, constants.hyper_p_dnn,
                constants.hyper_p_glm, y, X_encoded, constants.split_ratio)
            _model.compute_train_process()
            _model.compute_best_model()
            params['output'][y]['best_model'] = _model.best_model
            h2o.save_model(model=params['output'][y]['best_model'],
                           path=_path,
                           force=True)
            # shot down h2o instance. This project it runs on each available cores on your server or local comp.
            h2o.shutdown(prompt=False)

        if params['predict']:
            # prediction is initializing with trained model. batch size is crucial point at here
            params['output'][y]['predicted'] = prediction.get_prediction(
                params['output'][y]['model_path'], iters, params['pred_data'],
                params['prediction_batch_size'])
            # writing on a pickle the prediction values as array
            data_access.pred_write_reader(_path, y, True, params)
        else:
            # check existing path has the predictions
            params['output'][y]['predicted'] = data_access.pred_write_reader(
                _path, y, False, [])
Exemplo n.º 8
0
def top():
    aWeight = 0.5
    camera = cv2.VideoCapture(0)
    top, right, bottom, left = 10, 225, 300, 475
    num_frames = 0
    count = 0
    t = time.time()
    s = "First"
    X = '0'

    while (True):
        (grabbed, frame) = camera.read()
        frame = imutils.resize(frame, width=700)
        frame = cv2.flip(frame, 1)
        clone = frame.copy()
        (height, width) = frame.shape[:2]
        roi = frame[10:300, 225:475]
        gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (7, 7), 0)
        if num_frames < 30:
            run_avg(gray, aWeight)
        else:
            ret = ""
            hand = segment(gray)
            if hand is not None:
                (thresholded, segmented) = hand
                cv2.drawContours(clone, [segmented + (right, top)], -1,
                                 (0, 0, 255))
                # cv2.imshow("Thesholded", roi)
                __draw_label(clone, 'Count is = ' + str(num_frames), (20, 20),
                             (255, 255, 255))
                if (num_frames % 40 == 0):
                    count = count + 1
                    # cv2.imshow('f', frame)
                    if (count == 4):
                        count = 0
                        im = Image.fromarray(roi)
                        im.save('test.jpeg')
                        X = get_prediction('test.jpeg')
                        ret = ret + X + " "
                        print(X)
                        # draw the label into the frame
                        # Display the resulting frame
                        # cv2.imshow('Frame',clone)
                    print("amodh")
                    s = s + "A"
        __draw_label(clone, X, (25, 334), (255, 255, 255))

        cv2.rectangle(clone, (left, top), (right, bottom), (0, 255, 0), 2)
        num_frames += 1
        cv2.imshow("Video Feed", clone)
        keypress = cv2.waitKey(1) & 0xFF
        if keypress == ord("q"):
            return ret
Exemplo n.º 9
0
def evaluate():
    with open("../data/data_detect_local_evaluate_100.json") as json_file:
        data = json.load(json_file)
    data_index = 0

    total_match = []
    total_missing_blobs = 0
    total_extra_blobs = 0

    while str(data_index) in data:
        img = get_img(
            "../pictures/pictures_detect_local_evaluate_100/{}.png".format(
                data_index))
        boxes, probs, classification_logits, regression_values = get_prediction(
            img)

        raw_data = data[str(data_index)]
        all_blobs = raw_data["army"] + raw_data["enemy"]

        estimates = []
        for i in range(len(boxes)):
            if probs[i] > .9:
                box = get_final_box(boxes[i],
                                    regression_values[i],
                                    limit_border=False)
                classification_probs = tf.nn.softmax(
                    classification_logits[i]).numpy()
                match = []
                for i, t_blob in enumerate(all_blobs):
                    c_x = (box[0] + box[2]) / (2 * feature_size)
                    c_y = (box[1] + box[3]) / (2 * feature_size)
                    t_x = t_blob["x"]
                    t_y = t_blob["y"]
                    m = int(t_blob["alive"])
                    distance = math.sqrt((c_x - t_x)**2 + (c_y - t_y)**2)
                    m = m / (1 + distance)
                    label = 1 + statuses[t_blob["status"]] + 3 * int(i >= 3)
                    m = m * classification_probs[label]
                    match.append(m)
                estimates.append(match)

        output = []
        while len(estimates) != 0:
            if (np.max(estimates) < .2):
                break
            best_match = np.argmax(estimates)
            predicted_blob = best_match // 6
            target_blob = best_match % 6
            output.append(estimates[predicted_blob][target_blob])
            estimates.pop(predicted_blob)
            for match in estimates:
                match[target_blob] = 0

        alive_blobs = len([1 for b in all_blobs if b["alive"] == True])
        blobs_count_difference = alive_blobs - len(output)

        if len(output) == 0:
            picture_match = 0.
        else:
            picture_match = sum(output) / len(output)

        print("\n>>>>>> {}".format(data_index))
        print("{} blobs matching".format(len(output)))
        print("{}% average match".format(int(picture_match * 100)))
        print("{} blobs missed".format(max(0, blobs_count_difference)))
        print("{} extra predictions".format(max(0, -blobs_count_difference)))

        total_match.append(picture_match)
        total_missing_blobs += max(0, blobs_count_difference)
        total_extra_blobs += max(0, -blobs_count_difference)

        data_index += 1

    print("\n\n>>>>>> Summary for {} pictures".format(data_index))
    print("Average match: {}%".format(
        int(sum(total_match) / len(total_match) * 100)))
    print("Total missed blobs: {}".format(total_missing_blobs))
    print("Total extra predictions: {}".format(total_extra_blobs))
Exemplo n.º 10
0
def predict():
    if request.method == 'POST':
        file = request.files['file']
        img_bytes = file.read()
        class_id, class_name = get_prediction(image_bytes=img_bytes)
        return jsonify({'class_id': class_id, 'class_name': class_name})
Exemplo n.º 11
0
def callback_worker(call):
    prediction = get_prediction(call.data)
    if type(prediction) != str:
        prediction = prediction[0] + ' и ' + prediction[1]
    bot.send_message(call.from_user.id, 'В Москве сегодня ' + prediction)
Exemplo n.º 12
0
                hand = segment(gray)
                if hand is not None:
                    (thresholded, segmented) = hand
                    cv2.drawContours(clone, [segmented + (right, top)], -1,
                                     (0, 0, 255))
                    # cv2.imshow("Thesholded", roi)
                    __draw_label(clone, 'Count is = ' + str(num_frames),
                                 (20, 20), (255, 255, 255))
                    if (num_frames % 40 == 0):
                        count = count + 1
                        # cv2.imshow('f', frame)
                        if (count == 4):
                            count = 0
                            im = Image.fromarray(roi)
                            im.save('test.jpeg')
                            X = get_prediction('test.jpeg')
                            ts(X)
                            ret = ret + X + " "
                            print(X)
                            # draw the label into the frame
                            # Display the resulting frame
                            # cv2.imshow('Frame',clone)
                        s = s + "A"
            __draw_label(clone, X, (25, 334), (255, 255, 255))

            cv2.rectangle(clone, (left, top), (right, bottom), (0, 255, 0), 2)
            num_frames += 1
            cv2.imshow("Video Feed", clone)
            keypress = cv2.waitKey(1) & 0xFF
            if keypress == ord("q"):
                file1.write(ret)
Exemplo n.º 13
0
    time.sleep(10)
    print("正在读取价格……")
    #读取价格并生成输入数据
    if modeType == 0:
        symbol_id_list = prices.read_prices()
    else:
        symbol_id_list = prices.read_pricehistory(predict_batch_size)
    try:
        if len(symbol_id_list) == 0:
            continue
    except:
        continue
    print("正在执行预测……")
    # 预测并读取结果 
    while True:
        time.sleep(1)
        predict_files  = glob.glob(predict_file_pattern)
        predict_files_second  = glob.glob(predict_file_second_pattern)
        if len(predict_files) == 0 or len(predict_files_second) == 0:
            continue
        print("检测到预测文件:", predict_files[0])
        print("检测到预测文件2:", predict_files_second[0])
        time.sleep(2)
        if modeType == 0:
            prediction.get_prediction(symbol_id_list, predict_files[0])
        else:
            prediction.get_predictionhistory(symbol_id_list, predict_files[0], predict_files_second[0])
        break
    print("预测执行完毕!")
    time.sleep(20)
Exemplo n.º 14
0
def stopRecording():
    print("Stopped")
    get_prediction(get_numpyArray(), 10)
    stop_Recording()
    return jsonify({"hola":1})