Photon08/rps_computer_vison
1
1from ultralytics import YOLO2import random3import streamlit as st4from PIL import Image5import os6import gdown7 8def extract_user_input(image=None):9 10 11 id = "1e2pHejcp96q-NT9VmIDEY_hCA-tiFNef"12 output = "trained_model.pt"13 gdown.download(id = id, output = output, quiet=False)14 15 model = YOLO(output)16 17 result = model.predict(image)18 19 names = model.names20 det_cls = []21 for r in result:22 for c in r.boxes.cls:23 det_cls.append(names[int(c)])24 25 return det_cls[0]26 27 28def ai_choice():29 choice = random.randint(0,1000000000)30 31 if choice <=100000:32 choice = "Rock"33 elif choice >101 and choice <=1000000:34 choice = "Paper"35 else:36 choice = "Scissors"37 return choice38 39def winner(user_input,ai_input):40 41 if user_input == "Rock":42 if ai_input == "Scissors":43 return "Player 1"44 elif ai_input == "Paper":45 return "AI"46 else:47 return "Draw!!!"48 if user_input == "Paper":49 if ai_input == "Rock":50 return "Player 1"51 elif ai_input == "Scissors":52 return "AI"53 else:54 return "Draw!!!"55 if user_input == "Scissors":56 if ai_input == "Rock":57 return "AI"58 elif ai_input == "Paper":59 return "Player 1"60 else:61 return "Draw!!!"62 63 64def main():65 col1, col2 = st.columns(2)66 with st.container():67 st.header("Welcome to the Computer Vison powered Rock-Paper-Scissors Game!")68 st.caption("developed by Indranil Bhattacharyya")69 70 player_name = st.text_input("Please enter your name, Player!: ")71 72 image = st.camera_input("Please upload your image: ")73 74 if image:75 st.image(image)76 77 im = Image.open(image)78 rgb_im = im.convert("RGB")79 80 # exporting the image81 rgb_im.save("user_input.jpg")82 83 84 user_input = extract_user_input("user_input.jpg")85 user_input_front_end = player_name + " has selected: " + user_input86 87 st.code(user_input_front_end)88 ai_choice_var = ai_choice()89 ai_choice_front_end = "AI has selected: " + ai_choice_var90 st.code(ai_choice_front_end)91 if len(user_input)>0:92 winner_name = winner(user_input,ai_choice_var)93 if len(winner_name)!=0:94 with st.container():95 if winner_name == "Player 1":96 97 winner_front_end = player_name + " Wins!!!"98 99 st.success(winner_front_end)100 else:101 if winner_name == "AI":102 winner_front_end = winner_name + " Wins!!!"103 else:104 winner_front_end = "It's a " + winner_name105 106 st.error(winner_front_end)107 else:108 winner_name = ''109 110 111 112if __name__ == "__main__":113 main() 114 115 116 