from flask import Flask, request, jsonify
import math
import cv2
import os

app = Flask(__name__)

@app.route("/")
def indexfun():
    return "welcome"

@app.route("/predict",  methods = ['POST'])
def getStepCount():
    file = request.files['file']
    image_path = "./images/" + file.filename
    file.save(image_path)

    image = cv2.imread(image_path)
    gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

    gaussian_image = cv2.GaussianBlur(gray_image,(9,9),0,0)

    canny_image = cv2.Canny(gaussian_image,80,240,3)
    # canny_image = cv2.Canny(gaussian_image,50,120)

    output_image = cv2.cvtColor(canny_image, cv2.COLOR_GRAY2BGR)
    output_image2 = cv2.cvtColor(canny_image, cv2.COLOR_GRAY2BGR)
    output_image3 = cv2.cvtColor(canny_image, cv2.COLOR_GRAY2BGR)

    lines = list()

    lines = cv2.HoughLinesP(canny_image,1,math.pi/180,30,40,5)

    for i in range(0,len(lines)):
        line = lines[i][0]
        cv2.line(output_image,(line[0],line[1]),(line[2],line[3]),(0,0,255),3,5)


    y_values = list()
    x_values = list()

    # print(lines)
    # print("################")
    # print(lines[0][0]) #[ 25 189 167 189]
    # print(lines.shape)

    # remove vertical lines
    for i in range(0, len(lines)):
        line = lines[i][0]
        #line -> [ 25 189 167 189]
        #line -> y1-[1] -> 189
        #line -> y2-[3] -> 189

        if (abs(line[1] - line[3])) < 5:
            y_values.append([line[1],line[3]])
            x_values.append([line[0],line[2]])
        
        #line -> x1-[0] -> 25
        #line -> x2-[2] -> 167
        if (abs(line[0] - line[2])) > 100:
            y_values.append([line[1],line[3]])
            x_values.append([line[0],line[2]])

    # print(y_values)
    # print("################")
    # print(y_values[0]) #[189, 189]

    for i in range(0, len(y_values)):
        # y_ax -> [189, 189]
        y_ax = y_values[i]
        x_ax = x_values[i]

        cv2.line(output_image2,(x_ax[0],y_ax[0]),(x_ax[1],y_ax[1]),(0,0,255),3,5)

    # remove unwanted horizontal lines

    # print(y_values)
    # print("################")
    # print(y_values[0][0]) #189
    # # y_ax -> 189

    y_ax = list()
    y_ax.append(y_values[0][0])
    stair_count = 0
    flag = 1

    for i in range(0, len(y_values)):
        line = y_values[i]
        #line -> [189, 189]

        for j in range(0, len(y_ax)):
            # y_ax -> 189
            # This value will calculate with help of step height and width (15,40,60)

            step_heigth_mean = 15

            if (abs(y_ax[j] - line[1]) < step_heigth_mean):
                flag = 0

        if flag:
            cv2.line(output_image3,(0,line[1]),(output_image3.shape[1],line[1]),(0,0,255),3,5)
            stair_count = stair_count + 1
            y_ax.append(line[1])

        flag = 1


    print("Stair count :"+ str(stair_count))
    os.remove(image_path)
    return jsonify({"steps": str(stair_count)})
if __name__ == "__main__":
    app.run(debug=True)