from flask import Flask, jsonify, request
import os
import time
import cv2 
import numpy as np
from tensorflow import keras
### Load model using ke
json_file = open('tensorflow_model/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = keras.models.model_from_json(loaded_model_json)
loaded_model.load_weights("tensorflow_model/model.h5")
# RTSP_URL = 'rtsp://admin:admin123@192.168.31.190:554/cam/realmonitor?channel=8&subtype=0'

# creating a Flask app
app = Flask(__name__)
  
# on the terminal type: curl http://127.0.0.1:5000/
# returns hello world when we use GET.
# returns the data that we send when we use POST.
@app.route('/ai', methods = ['GET', 'POST'])
def with_parameters():
    url = request.args.get('url')
    if (request.args.get('subtype')):
      url = url+"&subtype="+request.args.get('subtype')
    RTSP_URL = url
    os.environ['OPENCV_FFMPEG_CAPTURE_OPTIONS'] = 'rtsp_transport;udp'
    if(request.method == 'GET'):
        #Capture Video from CCTV Camera using OpenCV 
      cap = cv2.VideoCapture(RTSP_URL, cv2.CAP_FFMPEG)
      if not cap.isOpened():
          print('Cannot open RTSP stream') ## checking RTSP stream 
          exit(-1)

      #Initializing Videowriter to save video
      # width, height = 700, 600
      # fps = 25
      # # fourcc = cv2.VideoWriter_fourcc(*'DIVX')
      # fourcc =cv2.VideoWriter_fourcc(*'MJPG')
      # # Create VideoWriter object
      # writer = cv2.VideoWriter(filename='video_output.avi',
      #                       fourcc=fourcc,
      #                       apiPreference=cv2.CAP_FFMPEG,
      #                       fps=float(fps),
      #                       frameSize=(width, height),
      #                       isColor=True)
      
      #Declaring Frame Rate to Control frame 
      frame_rate = 1
      prev = 0


      
      while True:
          _, frame = cap.read()  ##Read stream
          # writer.write(frame)         ##write Frame to save video 
          time_elapsed = time.time() - prev
          if time_elapsed > 1./frame_rate:        ##controlling Frame Rate
              prev = time.time()

              ## Preparing input for prediction
              image = cv2.resize(frame, (224, 224))   
              img = np.reshape(image, [1, 224, 224, 3])

              ## Give input value to model
              output=np.argmax(loaded_model.predict(img))
              if (output==0):
                  text ="Okey"
              else:
                  text = "Problem"
              return text
              # #Resize to show Video with output prediction4
              # image = cv2.resize(frame, (700, 550))
              # im=cv2.putText(img=image, text=text, org=(0, 50), fontFace=cv2.FONT_HERSHEY_TRIPLEX, fontScale=1.1, color=(0, 255, 255),thickness=1)
              # cv2.imshow("output",im)
              # if cv2.waitKey(1) == 27:
              #     cap.release()
              #     writer.release()
              #     cv2.destroyAllWindows()
              #     break
 


              

  
  
# driver function
if __name__ == '__main__':
  
    app.run(debug = True)