from io import StringIO
import numpy as np
from tensorflow.keras.models import model_from_json
import operator
import cv2
import sys, os

# Loading the model
json_file = open("model-bw.json", "r")
model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(model_json)
# load weights into new model
loaded_model.load_weights("model-bw.h5")
print("Loaded model from disk")

cap = cv2.VideoCapture(0)

# Category dictionary
map_to_labels = {0: 'rock', 1: 'paper', 2: 'scissor'}
prediction=[]

while True:
    _, frame = cap.read()
    # Simulating mirror image
    frame = cv2.flip(frame, 1)
    
    # Got this from collect-data.py
    # Coordinates of the ROI
    x1 = int(0.5*frame.shape[1])
    y1 = 10
    x2 = frame.shape[1]-10
    y2 = int(0.5*frame.shape[1])
    # Drawing the ROI
    # The increment/decrement by 1 is to compensate for the bounding box
    cv2.rectangle(frame, (x1-1, y1-1), (x2+1, y2+1), (255,0,0) ,1)
    # Extracting the ROI
    roi = frame[y1:y2, x1:x2]
    
    # Resizing the ROI so it can be fed to the model for prediction
    roi = cv2.resize(roi, (64, 64)) 
    roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
    _, test_image = cv2.threshold(roi, 120, 255, cv2.THRESH_BINARY)
    cv2.imshow("test", test_image)
    # Batch of 1
    result = loaded_model.predict(test_image.reshape(1, 64, 64, 1))
    prediction = {'paper': result[0][0],  #prs not rps becoz model is trained in such way
                  'rock': result[0][1], 
                  'scissor': result[0][2],
                  }
    # Sorting based on top prediction
    prediction = sorted(prediction.items(), key=operator.itemgetter(1), reverse=True)
    
    # Displaying the predictions
    cv2.putText(frame, prediction[0][0], (10, 120), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1)  
    cv2.putText(frame, "your move is : "+prediction[0][0], (10, 140), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1)  
    x=np.random.choice([0,1,2])
    cv2.putText(frame, "Bot move is : "+str(x), (10, 160), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,255), 1)
    res=""
    if prediction[0][0]=='rock':
        if x==1: 
            res="YOU LOOSE "
        elif x==0:
            res="Draw"
        else :
            res="YOU WON"
    elif prediction[0][0]=="paper":
        if x==2:
            res="YOU LOOSE"
        elif x==1:
            res="Draw"
        else :
            res="YOU WON"
    else :
        if x==0:
            res="YOU LOOSE"
        elif x==2:
            res="Draw"
        else :
            res="YOU WON"
    
    cv2.putText(frame, res , (10, 180), cv2.FONT_HERSHEY_PLAIN, 1, (255,255,0), 2)
    cv2.imshow("Frame", frame)
    
    interrupt = cv2.waitKey(10)
    if interrupt & 0xFF == 27: # esc key
        break
        
 
cap.release()
cv2.destroyAllWindows()