Update app.py
Browse files
app.py
CHANGED
|
@@ -1,23 +1,38 @@
|
|
|
|
|
| 1 |
import random
|
| 2 |
import csv
|
| 3 |
import numpy as np
|
| 4 |
import tensorflow as tf
|
|
|
|
| 5 |
from tensorflow.keras.models import Sequential
|
| 6 |
from tensorflow.keras.layers import LSTM, Dense, Embedding
|
| 7 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 8 |
from tensorflow.keras.preprocessing.text import Tokenizer
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# Mapping choices to numerical values
|
| 11 |
choices = {'rock': 0, 'paper': 1, 'scissors': 2}
|
| 12 |
rev_choices = {0: 'rock', 1: 'paper', 2: 'scissors'}
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def get_computer_choice(model, past_moves):
|
|
|
|
| 15 |
if len(past_moves) < 3:
|
| 16 |
-
return random.choice([
|
| 17 |
|
| 18 |
# Prepare input data for prediction
|
| 19 |
sequence = [choices[move] for move in past_moves[-3:]]
|
| 20 |
sequence = pad_sequences([sequence], maxlen=3)
|
|
|
|
| 21 |
prediction = model.predict(sequence, verbose=0)
|
| 22 |
predicted_choice = rev_choices[np.argmax(prediction)]
|
| 23 |
|
|
@@ -26,74 +41,92 @@ def get_computer_choice(model, past_moves):
|
|
| 26 |
return counter_choices[predicted_choice]
|
| 27 |
|
| 28 |
def get_winner(player, computer):
|
|
|
|
| 29 |
if player == computer:
|
| 30 |
return "It's a tie!"
|
| 31 |
-
elif (player ==
|
| 32 |
-
(player ==
|
| 33 |
-
(player ==
|
| 34 |
return "You win!"
|
| 35 |
else:
|
| 36 |
return "Computer wins!"
|
| 37 |
|
| 38 |
def save_move(player, computer, result):
|
| 39 |
-
|
|
|
|
| 40 |
writer = csv.writer(file)
|
| 41 |
writer.writerow([player, computer, result])
|
| 42 |
|
| 43 |
def load_data():
|
|
|
|
| 44 |
try:
|
| 45 |
-
with open(
|
| 46 |
reader = csv.reader(file)
|
| 47 |
next(reader) # Skip header
|
| 48 |
-
|
| 49 |
-
return data
|
| 50 |
except FileNotFoundError:
|
| 51 |
return []
|
| 52 |
|
| 53 |
def train_lstm_model(data):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
tokenizer = Tokenizer(num_words=3)
|
| 55 |
tokenizer.fit_on_texts(data)
|
| 56 |
sequences = tokenizer.texts_to_sequences(data)
|
|
|
|
| 57 |
X = pad_sequences(sequences, maxlen=3)
|
| 58 |
y = np.array([choices[move] for move in data[1:]])
|
| 59 |
|
| 60 |
model = Sequential([
|
| 61 |
Embedding(input_dim=3, output_dim=10, input_length=3),
|
| 62 |
LSTM(20, return_sequences=False),
|
| 63 |
-
Dense(3, activation=
|
| 64 |
])
|
| 65 |
-
model.compile(loss=
|
| 66 |
|
| 67 |
if len(X) > 1:
|
| 68 |
model.fit(X[:-1], y, epochs=10, verbose=0)
|
| 69 |
return model
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
past_moves
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
print("Invalid choice. Please try again.")
|
| 87 |
-
continue
|
| 88 |
-
|
| 89 |
computer_choice = get_computer_choice(model, past_moves)
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
if __name__ == "__main__":
|
| 99 |
-
|
|
|
|
| 1 |
+
import os
|
| 2 |
import random
|
| 3 |
import csv
|
| 4 |
import numpy as np
|
| 5 |
import tensorflow as tf
|
| 6 |
+
import gradio as gr
|
| 7 |
from tensorflow.keras.models import Sequential
|
| 8 |
from tensorflow.keras.layers import LSTM, Dense, Embedding
|
| 9 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 10 |
from tensorflow.keras.preprocessing.text import Tokenizer
|
| 11 |
|
| 12 |
+
# Disable GPU for Hugging Face Spaces
|
| 13 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 14 |
+
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
|
| 15 |
+
|
| 16 |
# Mapping choices to numerical values
|
| 17 |
choices = {'rock': 0, 'paper': 1, 'scissors': 2}
|
| 18 |
rev_choices = {0: 'rock', 1: 'paper', 2: 'scissors'}
|
| 19 |
|
| 20 |
+
# Ensure CSV exists
|
| 21 |
+
csv_filename = "game_moves.csv"
|
| 22 |
+
if not os.path.exists(csv_filename):
|
| 23 |
+
with open(csv_filename, mode='w', newline='') as file:
|
| 24 |
+
writer = csv.writer(file)
|
| 25 |
+
writer.writerow(["Player Choice", "Computer Choice", "Result"])
|
| 26 |
+
|
| 27 |
def get_computer_choice(model, past_moves):
|
| 28 |
+
""" Predicts player's next move and counteracts it. """
|
| 29 |
if len(past_moves) < 3:
|
| 30 |
+
return random.choice(["rock", "paper", "scissors"])
|
| 31 |
|
| 32 |
# Prepare input data for prediction
|
| 33 |
sequence = [choices[move] for move in past_moves[-3:]]
|
| 34 |
sequence = pad_sequences([sequence], maxlen=3)
|
| 35 |
+
|
| 36 |
prediction = model.predict(sequence, verbose=0)
|
| 37 |
predicted_choice = rev_choices[np.argmax(prediction)]
|
| 38 |
|
|
|
|
| 41 |
return counter_choices[predicted_choice]
|
| 42 |
|
| 43 |
def get_winner(player, computer):
|
| 44 |
+
""" Determines the winner of the game. """
|
| 45 |
if player == computer:
|
| 46 |
return "It's a tie!"
|
| 47 |
+
elif (player == "rock" and computer == "scissors") or \
|
| 48 |
+
(player == "scissors" and computer == "paper") or \
|
| 49 |
+
(player == "paper" and computer == "rock"):
|
| 50 |
return "You win!"
|
| 51 |
else:
|
| 52 |
return "Computer wins!"
|
| 53 |
|
| 54 |
def save_move(player, computer, result):
|
| 55 |
+
""" Saves game move to CSV file. """
|
| 56 |
+
with open(csv_filename, mode="a", newline="") as file:
|
| 57 |
writer = csv.writer(file)
|
| 58 |
writer.writerow([player, computer, result])
|
| 59 |
|
| 60 |
def load_data():
|
| 61 |
+
""" Loads past player moves from CSV file. """
|
| 62 |
try:
|
| 63 |
+
with open(csv_filename, mode="r") as file:
|
| 64 |
reader = csv.reader(file)
|
| 65 |
next(reader) # Skip header
|
| 66 |
+
return [row[0] for row in reader]
|
|
|
|
| 67 |
except FileNotFoundError:
|
| 68 |
return []
|
| 69 |
|
| 70 |
def train_lstm_model(data):
|
| 71 |
+
""" Trains an LSTM model to predict the player's next move. """
|
| 72 |
+
if len(data) < 4:
|
| 73 |
+
return None # Not enough data for meaningful training
|
| 74 |
+
|
| 75 |
tokenizer = Tokenizer(num_words=3)
|
| 76 |
tokenizer.fit_on_texts(data)
|
| 77 |
sequences = tokenizer.texts_to_sequences(data)
|
| 78 |
+
|
| 79 |
X = pad_sequences(sequences, maxlen=3)
|
| 80 |
y = np.array([choices[move] for move in data[1:]])
|
| 81 |
|
| 82 |
model = Sequential([
|
| 83 |
Embedding(input_dim=3, output_dim=10, input_length=3),
|
| 84 |
LSTM(20, return_sequences=False),
|
| 85 |
+
Dense(3, activation="softmax")
|
| 86 |
])
|
| 87 |
+
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
|
| 88 |
|
| 89 |
if len(X) > 1:
|
| 90 |
model.fit(X[:-1], y, epochs=10, verbose=0)
|
| 91 |
return model
|
| 92 |
|
| 93 |
+
# Load past moves and train model
|
| 94 |
+
past_moves = load_data()
|
| 95 |
+
model = train_lstm_model(past_moves) if len(past_moves) >= 4 else None
|
| 96 |
+
|
| 97 |
+
def play_game(player_choice):
|
| 98 |
+
""" Handles the game logic and returns the result. """
|
| 99 |
+
global past_moves, model
|
| 100 |
+
|
| 101 |
+
if player_choice not in choices:
|
| 102 |
+
return "Invalid choice. Choose rock, paper, or scissors."
|
| 103 |
+
|
| 104 |
+
# Ensure model exists before predicting
|
| 105 |
+
if model is None:
|
| 106 |
+
computer_choice = random.choice(["rock", "paper", "scissors"])
|
| 107 |
+
else:
|
|
|
|
|
|
|
|
|
|
| 108 |
computer_choice = get_computer_choice(model, past_moves)
|
| 109 |
+
|
| 110 |
+
result = get_winner(player_choice, computer_choice)
|
| 111 |
+
|
| 112 |
+
# Save the move
|
| 113 |
+
save_move(player_choice, computer_choice, result)
|
| 114 |
+
past_moves.append(player_choice)
|
| 115 |
+
|
| 116 |
+
# Retrain the model after each move
|
| 117 |
+
if len(past_moves) >= 4:
|
| 118 |
+
model = train_lstm_model(past_moves)
|
| 119 |
+
|
| 120 |
+
return f"Computer chose: {computer_choice}\n{result}"
|
| 121 |
+
|
| 122 |
+
# Gradio UI
|
| 123 |
+
iface = gr.Interface(
|
| 124 |
+
fn=play_game,
|
| 125 |
+
inputs=gr.Radio(["rock", "paper", "scissors"], label="Choose your move"),
|
| 126 |
+
outputs="text",
|
| 127 |
+
title="Rock, Paper, Scissors AI",
|
| 128 |
+
description="Play against an AI that learns from your moves and tries to beat you!"
|
| 129 |
+
)
|
| 130 |
|
| 131 |
if __name__ == "__main__":
|
| 132 |
+
iface.launch()
|