Dilanka Kasun commited on
Commit
999a889
·
1 Parent(s): 52c5dac
Files changed (2) hide show
  1. requirements.txt +8 -0
  2. run.py +164 -0
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ pymongo[srv]==3.12.0
2
+ numpy==1.21.3
3
+ pandas==1.3.3
4
+ scikit-learn==0.24.2
5
+ streamlit
6
+ tensorflow==2.7.0
7
+ protobuf==3.18.0
8
+ matplotlib
run.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from sklearn.preprocessing import StandardScaler
6
+ from pymongo import MongoClient
7
+ from pymongo.errors import ServerSelectionTimeoutError, AutoReconnect
8
+ import matplotlib.pyplot as plt
9
+ import time
10
+
11
+ # Replace these values with your MongoDB connection details
12
+ mongo_uri = "mongodb+srv://uorfot1138:a94DUMIAk3JYFj0t@cluster0.kenwsba.mongodb.net/?retryWrites=true&w=majority"
13
+ database_name = "game"
14
+ collection_name = "aviator"
15
+ prediction_history_collection_name = "aviator_prediction_history"
16
+
17
+ def connect_to_mongodb():
18
+ try:
19
+ client = MongoClient(mongo_uri)
20
+ database = client[database_name]
21
+ collection = database[collection_name]
22
+ prediction_history_collection = database[prediction_history_collection_name]
23
+ return collection, prediction_history_collection
24
+ except Exception as e:
25
+ st.error(f"Error connecting to MongoDB: {e}")
26
+
27
+ def retrieve_data_from_mongodb(collection):
28
+ data =[]
29
+ try:
30
+ cursor = collection.find()
31
+
32
+ for document in cursor:
33
+ _data = document['data']
34
+ __data = _data.split("x")
35
+ data.extend(__data)
36
+
37
+ except (ServerSelectionTimeoutError, AutoReconnect) as e:
38
+ st.error(f"MongoDB connection error: {e}")
39
+
40
+ return data
41
+
42
+ def save_prediction_to_mongodb(prediction, collection):
43
+ try:
44
+ collection.insert_one({'prediction': prediction})
45
+ except Exception as e:
46
+ st.error(f"Error saving prediction to MongoDB: {e}")
47
+
48
+ def get_prediction_history_from_mongodb(collection):
49
+ try:
50
+ cursor = collection.find()
51
+ prediction_history = [document['prediction'] for document in cursor]
52
+ return prediction_history
53
+ except Exception as e:
54
+ st.error(f"Error retrieving prediction history from MongoDB: {e}")
55
+ return []
56
+
57
+ def train_and_predict_aviator_model(aviator_game_history, prediction_history_collection, save_path='aviator_model'):
58
+ aviator_game_history = [float(value) if value.strip() else np.nan for value in aviator_game_history]
59
+
60
+ if not aviator_game_history:
61
+ st.warning("No valid data found.")
62
+ return None
63
+
64
+ # Interpolate missing values
65
+ aviator_game_history = np.array(aviator_game_history)
66
+ aviator_game_history = np.interp(np.arange(len(aviator_game_history)), np.arange(len(aviator_game_history))[~np.isnan(aviator_game_history)], aviator_game_history[~np.isnan(aviator_game_history)])
67
+
68
+ aviator_game_history = aviator_game_history.reshape(-1, 1)
69
+
70
+ # Normalize data to a consistent range
71
+ scaler = StandardScaler()
72
+ aviator_game_history_normalized = scaler.fit_transform(aviator_game_history)
73
+
74
+ # Get the prediction history from MongoDB
75
+ prediction_history = get_prediction_history_from_mongodb(prediction_history_collection)
76
+ prediction_history = np.array(prediction_history).reshape(-1, 1)
77
+
78
+ # Concatenate historical predictions with actual data
79
+ training_data = np.concatenate((aviator_game_history_normalized, prediction_history))
80
+
81
+ # Create sequences for training
82
+ sequence_length = 20 # Adjusted sequence length
83
+ X, y = [], []
84
+
85
+ for i in range(len(training_data) - sequence_length):
86
+ X.append(training_data[i:i + sequence_length])
87
+ y.append(training_data[i + sequence_length])
88
+
89
+ X, y = np.array(X), np.array(y)
90
+
91
+ model = tf.keras.Sequential([
92
+ tf.keras.layers.LSTM(128, activation='relu', input_shape=(sequence_length, 1), return_sequences=True),
93
+ tf.keras.layers.LSTM(64, activation='relu'),
94
+ tf.keras.layers.Dense(32, activation='relu'),
95
+ tf.keras.layers.Dense(1)
96
+ ])
97
+
98
+ model.compile(optimizer='adam', loss='mse')
99
+
100
+ model.fit(X, y, epochs=100, verbose=2)
101
+
102
+ # Predict the next sequence
103
+ last_sequence = aviator_game_history_normalized[-sequence_length:].reshape(1, sequence_length, 1)
104
+ predicted_sequence_normalized = model.predict(last_sequence)
105
+ predicted_sequence = scaler.inverse_transform(predicted_sequence_normalized)
106
+
107
+ # Apply a minimum value of 1
108
+ predicted_multiplier = np.maximum(predicted_sequence[0][0], 1.0)
109
+
110
+ # Save the prediction to MongoDB
111
+ save_prediction_to_mongodb(predicted_multiplier, prediction_history_collection)
112
+
113
+ # Save the model
114
+ model.save(save_path)
115
+ st.write(f"Model saved to {save_path}")
116
+
117
+ return predicted_multiplier
118
+
119
+ # Streamlit UI
120
+ st.title("Aviator Game Predictor")
121
+ st.write("This app predicts the multiplier for the next round of the Aviator Game.")
122
+
123
+ # Example usage:
124
+ collection, prediction_history_collection = connect_to_mongodb()
125
+ aviator_game_history = retrieve_data_from_mongodb(collection)
126
+
127
+ # Create a placeholder for the predicted multiplier
128
+ predicted_multiplier_placeholder = st.empty()
129
+
130
+ # Create a placeholder for the chart
131
+ chart_placeholder = st.empty()
132
+
133
+ # Loop to continuously predict and display the next multiplier
134
+ while True:
135
+ predicted_next_multiplier = train_and_predict_aviator_model(aviator_game_history, prediction_history_collection)
136
+
137
+ if predicted_next_multiplier is not None:
138
+ predicted_multiplier_placeholder.write(f'Predicted Next Multiplier: {predicted_next_multiplier}')
139
+
140
+ # Update the Aviator game history with the predicted value
141
+ aviator_game_history = np.append(aviator_game_history, predicted_next_multiplier)
142
+
143
+ # Get the prediction history from MongoDB
144
+ prediction_history = get_prediction_history_from_mongodb(prediction_history_collection)
145
+
146
+ # Plot the chart
147
+ plt.figure(figsize=(10, 6))
148
+ plt.plot(range(1, len(aviator_game_history) + 1), aviator_game_history, label='Actual Multiplier', marker='o')
149
+ plt.scatter(range(len(aviator_game_history), len(aviator_game_history) + len(prediction_history)), prediction_history, color='g', label='Predicted Multiplier')
150
+ plt.axvline(x=len(aviator_game_history), color='r', linestyle='--', label='Predicted Next Round')
151
+ plt.xlabel('Round')
152
+ plt.ylabel('Multiplier')
153
+ plt.title('Aviator Game Multiplier Prediction')
154
+ plt.legend()
155
+ chart_placeholder.pyplot(plt)
156
+
157
+ # Display the chart continuously
158
+ st.experimental_rerun()
159
+
160
+ else:
161
+ predicted_multiplier_placeholder.warning('Prediction failed due to lack of valid data.')
162
+
163
+ # Add a delay before the next iteration
164
+ time.sleep(8) # Adjust the delay as needed