-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
410 lines (356 loc) · 14.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import xgboost as xgb
from datetime import datetime
import time
import threading
import queue
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import os
import platform
# Page configuration
st.set_page_config(
page_title="CrashPredict AI",
page_icon="🎮",
layout="wide",
initial_sidebar_state="expanded"
)
# Initialize session state
if 'historical_data' not in st.session_state:
st.session_state.historical_data = pd.DataFrame()
if 'model' not in st.session_state:
st.session_state.model = None
if 'scaler' not in st.session_state:
st.session_state.scaler = StandardScaler()
if 'last_prediction' not in st.session_state:
st.session_state.last_prediction = None
if 'auto_update' not in st.session_state:
st.session_state.auto_update = False
if 'driver' not in st.session_state:
st.session_state.driver = None
# Custom CSS with light/dark mode support
st.markdown("""
<style>
/* Light mode styles */
[data-theme="light"] .stApp {
background-color: #ffffff;
color: #1E1E1E;
}
[data-theme="light"] .stButton>button {
background-color: #4CAF50;
color: white;
border-radius: 5px;
width: 100%;
}
[data-theme="light"] .prediction-box {
padding: 20px;
border-radius: 10px;
background-color: #f5f5f5;
margin: 10px 0;
border: 1px solid #ddd;
}
[data-theme="light"] .latest-crash {
font-size: 24px;
font-weight: bold;
padding: 15px;
border-radius: 10px;
background-color: #f5f5f5;
margin: 10px 0;
text-align: center;
border: 1px solid #ddd;
}
/* Dark mode styles */
[data-theme="dark"] .stApp {
background-color: #1E1E1E;
color: white;
}
[data-theme="dark"] .stButton>button {
background-color: #4CAF50;
color: white;
border-radius: 5px;
width: 100%;
}
[data-theme="dark"] .prediction-box {
padding: 20px;
border-radius: 10px;
background-color: #2E2E2E;
margin: 10px 0;
border: 1px solid #444;
}
[data-theme="dark"] .latest-crash {
font-size: 24px;
font-weight: bold;
padding: 15px;
border-radius: 10px;
background-color: #2E2E2E;
margin: 10px 0;
text-align: center;
border: 1px solid #444;
}
/* Common styles */
.stButton>button:hover {
background-color: #45a049;
}
.crash-value {
font-size: 2em;
font-weight: bold;
}
.confidence {
color: var(--text-color);
font-size: 1.1em;
}
.recommended-bet {
margin-top: 10px;
padding: 10px;
border-radius: 5px;
background-color: rgba(76, 175, 80, 0.1);
}
</style>
""", unsafe_allow_html=True)
def get_chrome_path():
if platform.system() == "Windows":
# Common Chrome installation paths on Windows
paths = [
os.path.expandvars(r"%ProgramFiles%\Google\Chrome\Application\chrome.exe"),
os.path.expandvars(r"%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe"),
os.path.expandvars(r"%LocalAppData%\Google\Chrome\Application\chrome.exe")
]
for path in paths:
if os.path.exists(path):
return path
st.error("Chrome not found. Please ensure Chrome is installed in the default location.")
return None
else:
st.error("This application currently supports Windows only.")
return None
def initialize_driver():
if st.session_state.driver is None:
try:
chrome_path = get_chrome_path()
if not chrome_path:
return None
chrome_options = Options()
chrome_options.binary_location = chrome_path
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_experimental_option('useAutomationExtension', False)
try:
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
# Add stealth mode JavaScript
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.execute_script("window.chrome = { runtime: {} };")
# Set a proper user agent
driver.execute_cdp_cmd('Network.setUserAgentOverride', {
"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
})
# Try to load the website
driver.get("https://1xbet.com/en/allgamesentrance/crash")
time.sleep(5) # Allow page to load
# Verify the page loaded correctly
if "crash" in driver.current_url.lower():
st.session_state.driver = driver
return driver
else:
st.error("Failed to load the crash game page. Please try again.")
driver.quit()
return None
except Exception as e:
st.error(f"Failed to load website: {str(e)}")
if 'driver' in locals():
driver.quit()
return None
except Exception as e:
st.error(f"Failed to initialize Chrome driver: {str(e)}")
return None
return st.session_state.driver
class CrashGamePredictor:
def __init__(self):
self.model = st.session_state.model
self.scaler = st.session_state.scaler
def scrape_latest_game(self):
"""Scrape the latest crash point from 1xbet"""
try:
driver = st.session_state.driver
if driver is None:
driver = initialize_driver()
if driver is None:
return None
# Wait for the crash point element to be visible
try:
crash_element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "div.crash__value"))
)
# Extract the crash point value (remove the 'x' suffix)
crash_text = crash_element.text.strip()
if 'x' in crash_text:
crash_point = float(crash_text.replace('x', ''))
else:
crash_point = float(crash_text)
latest_data = {
'timestamp': pd.Timestamp.now(),
'crash_point': crash_point
}
return pd.Series(latest_data)
except Exception as e:
st.error(f"Error finding crash value: {str(e)}")
cleanup_driver()
return None
except Exception as e:
st.error(f"Error scraping data: {str(e)}")
cleanup_driver()
return None
def predict_crash_point(self, current_data):
if self.model is None or len(current_data) < 5:
# Provide a simple prediction when not enough data
recent_crashes = current_data['crash_point'].tail(5)
predicted_value = max(1.1, min(2.0, recent_crashes.mean() * 0.9))
confidence = 50.0 # Lower confidence when no model
return predicted_value, confidence
X, _ = self.prepare_features(current_data.tail(10))
if X is None:
return None, None
X_latest = X.iloc[-1:].copy()
X_scaled = self.scaler.transform(X_latest)
# Predict crash point range
predicted_value = self.model.predict(X_scaled)[0]
predicted_value = max(1.1, min(predicted_value, 10.0)) # Constrain prediction
# Calculate confidence based on recent prediction accuracy
recent_predictions = current_data['crash_point'].tail(5)
confidence = max(0, min(100, 100 - recent_predictions.std() * 10))
return predicted_value, confidence
def prepare_features(self, data):
if len(data) < 1:
return None, None
# Feature engineering
data['hour'] = data['timestamp'].dt.hour
data['minute'] = data['timestamp'].dt.minute
data['rolling_avg_crash'] = data['crash_point'].rolling(window=5, min_periods=1).mean()
data['rolling_std_crash'] = data['crash_point'].rolling(window=5, min_periods=1).std()
data['rolling_min_crash'] = data['crash_point'].rolling(window=5, min_periods=1).min()
data['rolling_max_crash'] = data['crash_point'].rolling(window=5, min_periods=1).max()
features = ['hour', 'minute', 'rolling_avg_crash', 'rolling_std_crash',
'rolling_min_crash', 'rolling_max_crash']
X = data[features].fillna(0)
y = (data['crash_point'] >= data['crash_point'].mean()).astype(int)
return X, y
def train_model(self, data):
X, y = self.prepare_features(data)
if X is None or len(X) < 10:
return None
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale features
X_train_scaled = self.scaler.fit_transform(X_train)
# Train XGBoost model
self.model = xgb.XGBRegressor(
n_estimators=100,
learning_rate=0.1,
max_depth=3,
random_state=42
)
self.model.fit(X_train_scaled, y_train)
# Save model and scaler to session state
st.session_state.model = self.model
st.session_state.scaler = self.scaler
return True
def cleanup_driver():
if st.session_state.driver is not None:
st.session_state.driver.quit()
st.session_state.driver = None
def update_data():
predictor = CrashGamePredictor()
latest_data = predictor.scrape_latest_game()
if latest_data is not None:
# Add to historical data
st.session_state.historical_data = pd.concat([
st.session_state.historical_data,
pd.DataFrame([latest_data])
]).tail(100) # Keep last 100 records
# Train model periodically
if len(st.session_state.historical_data) >= 10:
predictor.train_model(st.session_state.historical_data)
# Make prediction
predicted_crash, confidence = predictor.predict_crash_point(st.session_state.historical_data)
if predicted_crash is not None:
st.session_state.last_prediction = {
'crash_point': predicted_crash,
'confidence': confidence
}
def main():
st.title("🎮 CrashPredict AI - Live Predictions")
# Sidebar controls
with st.sidebar:
st.header("Settings")
auto_update = st.toggle("Enable Live Updates", value=st.session_state.auto_update)
update_interval = st.slider("Update Interval (seconds)", 1, 10, 2)
if auto_update != st.session_state.auto_update:
st.session_state.auto_update = auto_update
if not auto_update:
cleanup_driver()
st.rerun()
# Main content area
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("Live Game Data")
if len(st.session_state.historical_data) > 0:
latest_crash = st.session_state.historical_data['crash_point'].iloc[-1]
crash_color = "#4CAF50" if latest_crash >= 2.0 else "#ff4444"
st.markdown(f"""
<div class='latest-crash'>
Latest Crash Point: <span class='crash-value' style='color: {crash_color}'>{latest_crash:.2f}x</span>
</div>
""", unsafe_allow_html=True)
# Recent games table with formatted values
if not st.session_state.historical_data.empty:
display_df = st.session_state.historical_data.tail(10).copy()
display_df['crash_point'] = display_df['crash_point'].apply(lambda x: f"{x:.4f}x")
display_df['timestamp'] = display_df['timestamp'].dt.strftime('%H:%M:%S')
st.dataframe(
display_df[['timestamp', 'crash_point']],
hide_index=True,
use_container_width=True
)
with col2:
st.subheader("Next Crash Prediction")
# Always show prediction box, even with default values
if not st.session_state.last_prediction:
st.session_state.last_prediction = {
'crash_point': 1.5,
'confidence': 50.0
}
pred = st.session_state.last_prediction
recommended_bet = max(1.1, min(pred['crash_point'] - 0.5, 2.0))
st.markdown(f"""
<div class='prediction-box'>
<h3>Predicted Crash Point</h3>
<div class='crash-value' style='color: #4CAF50'>{pred['crash_point']:.2f}x</div>
<div class='confidence'>Confidence: {pred['confidence']:.1f}%</div>
<div class='recommended-bet'>
<strong style='color: #4CAF50'>Recommended Bet: {recommended_bet:.2f}x</strong>
<p style='font-size: 0.8em; opacity: 0.8;'>Based on pattern analysis and risk assessment</p>
</div>
</div>
""", unsafe_allow_html=True)
# Auto-update loop
if st.session_state.auto_update:
update_data()
time.sleep(update_interval)
st.rerun()
if __name__ == "__main__":
main()
# Cleanup on app shutdown
if st.session_state.driver is not None:
cleanup_driver()