Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,7 @@ import os
|
|
| 5 |
import requests
|
| 6 |
import datetime
|
| 7 |
import time
|
|
|
|
| 8 |
from sklearn.model_selection import train_test_split
|
| 9 |
from sklearn.utils.class_weight import compute_class_weight
|
| 10 |
from tensorflow.keras.models import Sequential, load_model
|
|
@@ -13,11 +14,13 @@ import tensorflow as tf
|
|
| 13 |
|
| 14 |
tf.get_logger().setLevel('ERROR')
|
| 15 |
|
|
|
|
| 16 |
DATA_DIR = "data"
|
| 17 |
CSV_FILE = os.path.join(DATA_DIR, "wingo_data.csv")
|
| 18 |
MODEL_FILE = os.path.join(DATA_DIR, "wingo_model.h5")
|
| 19 |
HISTORY_URL = "https://draw.ar-lottery01.com/WinGo/WinGo_3M/GetHistoryIssuePage.json"
|
| 20 |
-
|
|
|
|
| 21 |
THRESHOLD = 0.55
|
| 22 |
HEADERS = {
|
| 23 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
|
@@ -26,6 +29,14 @@ HEADERS = {
|
|
| 26 |
'Accept': 'application/json, text/plain, */*',
|
| 27 |
}
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
def fetch_history():
|
| 30 |
try:
|
| 31 |
resp = requests.get(HISTORY_URL, headers=HEADERS, timeout=15)
|
|
@@ -36,40 +47,37 @@ def fetch_history():
|
|
| 36 |
print(f"History fetch error: {e}")
|
| 37 |
return []
|
| 38 |
|
| 39 |
-
def
|
| 40 |
-
"""Current live period = latest completed period + 1
|
| 41 |
items = fetch_history()
|
| 42 |
if items:
|
| 43 |
-
|
| 44 |
-
if
|
| 45 |
try:
|
| 46 |
-
|
| 47 |
-
return next_period
|
| 48 |
except:
|
| 49 |
pass
|
| 50 |
-
#
|
| 51 |
if os.path.exists(CSV_FILE):
|
| 52 |
-
|
| 53 |
-
if len(
|
| 54 |
-
|
| 55 |
try:
|
| 56 |
-
|
| 57 |
-
return next_period
|
| 58 |
except:
|
| 59 |
pass
|
| 60 |
return "?"
|
| 61 |
|
| 62 |
-
def
|
| 63 |
-
|
|
|
|
| 64 |
# Load existing CSV
|
| 65 |
if os.path.exists(CSV_FILE):
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
print(f"Loaded CSV: {len(df)} records")
|
| 69 |
else:
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# Merge latest history from API
|
| 73 |
items = fetch_history()
|
| 74 |
if items:
|
| 75 |
new_records = []
|
|
@@ -86,52 +94,61 @@ def load_and_train():
|
|
| 86 |
'timestamp': datetime.datetime.now().isoformat()
|
| 87 |
})
|
| 88 |
df_new = pd.DataFrame(new_records)
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
print(f"
|
| 93 |
# Train model if enough data
|
| 94 |
-
if len(
|
| 95 |
-
|
| 96 |
X, y = [], []
|
| 97 |
-
for i in range(len(
|
| 98 |
-
X.append(
|
| 99 |
-
y.append(
|
| 100 |
X = np.array(X).reshape(-1, SEQUENCE_LEN, 1)
|
| 101 |
y = np.array(y)
|
| 102 |
if len(X) >= 5:
|
| 103 |
class_weights = compute_class_weight('balanced', classes=np.unique(y), y=y)
|
| 104 |
-
|
| 105 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 106 |
-
|
| 107 |
-
LSTM(
|
| 108 |
-
Dropout(0.2),
|
| 109 |
-
LSTM(32),
|
| 110 |
Dropout(0.2),
|
| 111 |
Dense(1, activation='sigmoid')
|
| 112 |
])
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
loss, acc =
|
| 117 |
-
print(f"Model
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
# Initial
|
| 123 |
print("Starting WinGo 3-Minute Predictor...")
|
| 124 |
-
|
|
|
|
|
|
|
| 125 |
|
| 126 |
def get_live_prediction():
|
| 127 |
-
"""Called every 30 seconds to refresh the prediction."""
|
| 128 |
if model is None or df is None or len(df) < SEQUENCE_LEN:
|
| 129 |
-
period =
|
| 130 |
return f"⏳ Live period {period}: Not enough data yet (need {SEQUENCE_LEN} records)"
|
| 131 |
-
period =
|
| 132 |
try:
|
| 133 |
-
|
| 134 |
-
inp = np.array(
|
| 135 |
prob = float(model.predict(inp, verbose=0)[0][0])
|
| 136 |
pred = "BIG" if prob > THRESHOLD else "SMALL"
|
| 137 |
conf = max(prob, 1-prob) * 100
|
|
@@ -139,10 +156,10 @@ def get_live_prediction():
|
|
| 139 |
except Exception as e:
|
| 140 |
return f"Error: {e}"
|
| 141 |
|
| 142 |
-
# Gradio UI
|
| 143 |
with gr.Blocks(title="WinGo 3-Minute Predictor") as demo:
|
| 144 |
-
gr.Markdown("# 🎯 WinGo 3
|
| 145 |
-
gr.Markdown("Automatically fetches latest data and updates prediction every 30 seconds.")
|
| 146 |
output = gr.Textbox(label="Live Prediction", value=get_live_prediction(), interactive=False)
|
| 147 |
demo.load(fn=get_live_prediction, outputs=output, every=30)
|
| 148 |
|
|
|
|
| 5 |
import requests
|
| 6 |
import datetime
|
| 7 |
import time
|
| 8 |
+
import threading
|
| 9 |
from sklearn.model_selection import train_test_split
|
| 10 |
from sklearn.utils.class_weight import compute_class_weight
|
| 11 |
from tensorflow.keras.models import Sequential, load_model
|
|
|
|
| 14 |
|
| 15 |
tf.get_logger().setLevel('ERROR')
|
| 16 |
|
| 17 |
+
# ========== CONFIG ==========
|
| 18 |
DATA_DIR = "data"
|
| 19 |
CSV_FILE = os.path.join(DATA_DIR, "wingo_data.csv")
|
| 20 |
MODEL_FILE = os.path.join(DATA_DIR, "wingo_model.h5")
|
| 21 |
HISTORY_URL = "https://draw.ar-lottery01.com/WinGo/WinGo_3M/GetHistoryIssuePage.json"
|
| 22 |
+
LIVE_URL = "https://draw.ar-lottery01.com/WinGo/WinGo_3M.json"
|
| 23 |
+
SEQUENCE_LEN = 5
|
| 24 |
THRESHOLD = 0.55
|
| 25 |
HEADERS = {
|
| 26 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
|
|
|
| 29 |
'Accept': 'application/json, text/plain, */*',
|
| 30 |
}
|
| 31 |
|
| 32 |
+
# Global variables
|
| 33 |
+
model = None
|
| 34 |
+
df = None
|
| 35 |
+
last_update_time = 0
|
| 36 |
+
|
| 37 |
+
# ------------------------------
|
| 38 |
+
# Helper functions
|
| 39 |
+
# ------------------------------
|
| 40 |
def fetch_history():
|
| 41 |
try:
|
| 42 |
resp = requests.get(HISTORY_URL, headers=HEADERS, timeout=15)
|
|
|
|
| 47 |
print(f"History fetch error: {e}")
|
| 48 |
return []
|
| 49 |
|
| 50 |
+
def get_current_live_period():
|
| 51 |
+
"""Current live period = latest completed period + 1"""
|
| 52 |
items = fetch_history()
|
| 53 |
if items:
|
| 54 |
+
latest = items[0].get('issueNumber')
|
| 55 |
+
if latest:
|
| 56 |
try:
|
| 57 |
+
return str(int(latest) + 1).zfill(len(latest))
|
|
|
|
| 58 |
except:
|
| 59 |
pass
|
| 60 |
+
# fallback: CSV last period + 1
|
| 61 |
if os.path.exists(CSV_FILE):
|
| 62 |
+
df_local = pd.read_csv(CSV_FILE)
|
| 63 |
+
if len(df_local) > 0:
|
| 64 |
+
last = df_local['period'].iloc[-1]
|
| 65 |
try:
|
| 66 |
+
return str(int(last) + 1).zfill(len(last))
|
|
|
|
| 67 |
except:
|
| 68 |
pass
|
| 69 |
return "?"
|
| 70 |
|
| 71 |
+
def update_model_and_data():
|
| 72 |
+
global model, df, last_update_time
|
| 73 |
+
print("Updating model and data...")
|
| 74 |
# Load existing CSV
|
| 75 |
if os.path.exists(CSV_FILE):
|
| 76 |
+
df_local = pd.read_csv(CSV_FILE)
|
| 77 |
+
df_local['period'] = df_local['period'].astype(str)
|
|
|
|
| 78 |
else:
|
| 79 |
+
df_local = pd.DataFrame(columns=['period','number','category','timestamp'])
|
| 80 |
+
# Fetch fresh history (up to 500 records)
|
|
|
|
| 81 |
items = fetch_history()
|
| 82 |
if items:
|
| 83 |
new_records = []
|
|
|
|
| 94 |
'timestamp': datetime.datetime.now().isoformat()
|
| 95 |
})
|
| 96 |
df_new = pd.DataFrame(new_records)
|
| 97 |
+
df_local = pd.concat([df_local, df_new], ignore_index=True)
|
| 98 |
+
df_local = df_local.drop_duplicates(subset=['period'], keep='last')
|
| 99 |
+
df_local.to_csv(CSV_FILE, index=False)
|
| 100 |
+
print(f"CSV updated. Total records: {len(df_local)}")
|
| 101 |
# Train model if enough data
|
| 102 |
+
if len(df_local) >= SEQUENCE_LEN + 5:
|
| 103 |
+
data_vals = df_local['category'].values[-200:]
|
| 104 |
X, y = [], []
|
| 105 |
+
for i in range(len(data_vals) - SEQUENCE_LEN):
|
| 106 |
+
X.append(data_vals[i:i+SEQUENCE_LEN])
|
| 107 |
+
y.append(data_vals[i+SEQUENCE_LEN])
|
| 108 |
X = np.array(X).reshape(-1, SEQUENCE_LEN, 1)
|
| 109 |
y = np.array(y)
|
| 110 |
if len(X) >= 5:
|
| 111 |
class_weights = compute_class_weight('balanced', classes=np.unique(y), y=y)
|
| 112 |
+
cw = {0: class_weights[0], 1: class_weights[1]}
|
| 113 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 114 |
+
new_model = Sequential([
|
| 115 |
+
LSTM(32, input_shape=(SEQUENCE_LEN,1)),
|
|
|
|
|
|
|
| 116 |
Dropout(0.2),
|
| 117 |
Dense(1, activation='sigmoid')
|
| 118 |
])
|
| 119 |
+
new_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
| 120 |
+
new_model.fit(X_train, y_train, epochs=20, batch_size=16, validation_data=(X_test, y_test),
|
| 121 |
+
class_weight=cw, verbose=0)
|
| 122 |
+
loss, acc = new_model.evaluate(X_test, y_test, verbose=0)
|
| 123 |
+
print(f"Model accuracy: {acc*100:.2f}%")
|
| 124 |
+
new_model.save(MODEL_FILE)
|
| 125 |
+
model = new_model
|
| 126 |
+
df = df_local
|
| 127 |
+
last_update_time = time.time()
|
| 128 |
+
print("Update complete.")
|
| 129 |
+
else:
|
| 130 |
+
print(f"Not enough data: {len(df_local)} records")
|
| 131 |
+
|
| 132 |
+
# Background thread: update every 60 seconds (fetch new results)
|
| 133 |
+
def periodic_update():
|
| 134 |
+
while True:
|
| 135 |
+
time.sleep(60)
|
| 136 |
+
update_model_and_data()
|
| 137 |
|
| 138 |
+
# Initial load on startup
|
| 139 |
print("Starting WinGo 3-Minute Predictor...")
|
| 140 |
+
update_model_and_data()
|
| 141 |
+
thread = threading.Thread(target=periodic_update, daemon=True)
|
| 142 |
+
thread.start()
|
| 143 |
|
| 144 |
def get_live_prediction():
|
|
|
|
| 145 |
if model is None or df is None or len(df) < SEQUENCE_LEN:
|
| 146 |
+
period = get_current_live_period()
|
| 147 |
return f"⏳ Live period {period}: Not enough data yet (need {SEQUENCE_LEN} records)"
|
| 148 |
+
period = get_current_live_period()
|
| 149 |
try:
|
| 150 |
+
last5 = df['category'].tail(SEQUENCE_LEN).tolist()
|
| 151 |
+
inp = np.array(last5).reshape(1, SEQUENCE_LEN, 1)
|
| 152 |
prob = float(model.predict(inp, verbose=0)[0][0])
|
| 153 |
pred = "BIG" if prob > THRESHOLD else "SMALL"
|
| 154 |
conf = max(prob, 1-prob) * 100
|
|
|
|
| 156 |
except Exception as e:
|
| 157 |
return f"Error: {e}"
|
| 158 |
|
| 159 |
+
# Gradio UI – auto‑refresh every 30 seconds
|
| 160 |
with gr.Blocks(title="WinGo 3-Minute Predictor") as demo:
|
| 161 |
+
gr.Markdown("# 🎯 WinGo 3‑Minute Game Predictor")
|
| 162 |
+
gr.Markdown("Automatically fetches latest data every minute, retrains, and updates prediction every 30 seconds.")
|
| 163 |
output = gr.Textbox(label="Live Prediction", value=get_live_prediction(), interactive=False)
|
| 164 |
demo.load(fn=get_live_prediction, outputs=output, every=30)
|
| 165 |
|