def predict():
    # initialize the data dictionary that will be returned from the
    # view
    data = {"success": False}
    global graph
    global sess

    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            file = flask.request.files["image"]
            print(file.filename)
            path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(path)

            sitk_image, _ = load_image(path)

            image = preprocess_sitk_image_for_slice_detection(sitk_image)

            spacing = sitk_image.GetSpacing()
            print(image.shape)

            with graph.as_default():
                set_session(sess)
                preds = model.predict(image)

            pred_z, prob = decode_slice_detection_prediction(preds)
            slice_z = adjust_detected_position_spacing(pred_z, spacing)

            print('Slice detected at position {} with confidence {}'.format(slice_z, prob))

            data["predictions"] = [{'filename': file.filename, 'slice_z': slice_z, 'probability': prob}]

            # indicate that the request was a success
            data["success"] = True

    # return the data dictionary as a JSON response
    return flask.jsonify(data)
def process_file(image_path, filename, prob_threshold=0.1):
    global segmentation_model
    global slice_detection_model
    print(image_path)

    pred_id = uuid.uuid4().hex
    results = {"success": False, "prediction": {'id': pred_id}}

    try:
        sitk_image, _ = load_image(image_path)
    except:
        return 1

    image2d, image2d_preview = preprocess_sitk_image_for_slice_detection(
        sitk_image)
    image3d = sitk.GetArrayFromImage(sitk_image)

    spacing = sitk_image.GetSpacing()
    size = list(sitk_image.GetSize())

    with graph.as_default():
        set_session(sess)
        preds = slice_detection_model.predict(image2d)

    pred_z, prob = decode_slice_detection_prediction(preds)
    slice_z = adjust_detected_position_spacing(pred_z, spacing)

    slice_detected = prob > prob_threshold

    if slice_detected:
        results["prediction"]["slice_z"] = slice_z

        slice_image = image3d[slice_z, :, :]

        with graph.as_default():
            set_session(sess)
            seg_image = segmentation_model.predict(
                preprocess_test_image(slice_image[np.newaxis, :, :,
                                                  np.newaxis]))
            seg_image = seg_image[0]

        out_seg_image = np.flipud(
            blend2d(np.squeeze(preprocess_test_image(slice_image)),
                    np.squeeze(seg_image > 0.5), 0.5))
        image2d_preview = place_line_on_img(image2d_preview,
                                            pred_z,
                                            pred_z,
                                            r=1)

        cv2.imwrite(f'{settings.UPLOAD_FOLDER}/{filename}_slice-{pred_id}.jpg',
                    to256(np.squeeze(preprocess_test_image(slice_image))))
        cv2.imwrite(
            f'{settings.UPLOAD_FOLDER}/{filename}_frontal-{pred_id}.jpg',
            to256(np.squeeze(image2d_preview)))
        cv2.imwrite(f'{settings.UPLOAD_FOLDER}/{filename}_seg-{pred_id}.jpg',
                    to256(np.squeeze(out_seg_image)))

        results["prediction"]["muscle_attenuation"] = '{0:.2f} HU'.format(
            compute_muscle_attenuation(slice_image,
                                       np.squeeze(seg_image > 0.5)))
        results["prediction"]["muscle_area"] = '{0:.2f}'.format(
            compute_muscle_area(np.squeeze(seg_image > 0.5),
                                spacing,
                                units='cm'))
        results["prediction"]["slice_prob"] = '{0:.2f}%'.format(100 * prob)

        results["success"] = True

    if results["success"]:
        result_str = 'Slice detected at position {0} of {1} with {2:.2f}% confidence '.format(
            slice_z, size[2], 100 * prob)
    else:
        result_str = 'Slice not detected'

    results["prediction"]["str"] = result_str
    return results
                        }

                        sitk_image, _ = load_image(image_path)

                        image2d, image2d_preview = preprocess_sitk_image_for_slice_detection(
                            sitk_image)
                        image3d = sitk.GetArrayFromImage(sitk_image)

                        spacing = sitk_image.GetSpacing()
                        size = list(sitk_image.GetSize())

                        with graph.as_default():
                            set_session(sess)
                            preds = slice_detection_model.predict(image2d)

                        pred_z, prob = decode_slice_detection_prediction(preds)
                        slice_z = adjust_detected_position_spacing(
                            pred_z, spacing)

                        slice_detected = prob > prob_threshold
                        #print(slice_z)
                        if slice_detected:
                            results["prediction"]["slice_z"] = slice_z
                            results["prediction"][
                                "slice_prob"] = '{0:.2f}%'.format(100 * prob)
                            results["success"] = True

                            #creating the (2) jpeg imageS of slice position and L3 slice
                            #######################################
                            image = image3d
                            slice_image = image[slice_z, :, :]