Ahmad140 commited on
Commit
d0e99cf
·
verified ·
1 Parent(s): 0e0f705

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -53
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
- SEQUENCE_LEN = 10
 
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 get_current_period():
40
- """Current live period = latest completed period + 1 (periods are sequential numbers)"""
41
  items = fetch_history()
42
  if items:
43
- latest_period = items[0].get('issueNumber')
44
- if latest_period:
45
  try:
46
- next_period = str(int(latest_period) + 1).zfill(len(latest_period))
47
- return next_period
48
  except:
49
  pass
50
- # Fallback: use last period from CSV + 1
51
  if os.path.exists(CSV_FILE):
52
- df = pd.read_csv(CSV_FILE)
53
- if len(df) > 0:
54
- last_period = df['period'].iloc[-1]
55
  try:
56
- next_period = str(int(last_period) + 1).zfill(len(last_period))
57
- return next_period
58
  except:
59
  pass
60
  return "?"
61
 
62
- def load_and_train():
63
- """Load CSV, merge new history, retrain model, save."""
 
64
  # Load existing CSV
65
  if os.path.exists(CSV_FILE):
66
- df = pd.read_csv(CSV_FILE)
67
- df['period'] = df['period'].astype(str)
68
- print(f"Loaded CSV: {len(df)} records")
69
  else:
70
- df = pd.DataFrame(columns=['period','number','category','timestamp'])
71
- print("No CSV found, starting fresh.")
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
- df = pd.concat([df, df_new], ignore_index=True)
90
- df = df.drop_duplicates(subset=['period'], keep='last')
91
- df.to_csv(CSV_FILE, index=False)
92
- print(f"After merge: {len(df)} total records")
93
  # Train model if enough data
94
- if len(df) >= SEQUENCE_LEN + 5:
95
- data = df['category'].values[-500:]
96
  X, y = [], []
97
- for i in range(len(data) - SEQUENCE_LEN):
98
- X.append(data[i:i+SEQUENCE_LEN])
99
- y.append(data[i+SEQUENCE_LEN])
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
- cw_dict = {0: class_weights[0], 1: class_weights[1]}
105
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
106
- model = Sequential([
107
- LSTM(64, return_sequences=True, input_shape=(SEQUENCE_LEN,1)),
108
- Dropout(0.2),
109
- LSTM(32),
110
  Dropout(0.2),
111
  Dense(1, activation='sigmoid')
112
  ])
113
- model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
114
- model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test),
115
- class_weight=cw_dict, verbose=0)
116
- loss, acc = model.evaluate(X_test, y_test, verbose=0)
117
- print(f"Model validation accuracy: {acc*100:.2f}%")
118
- model.save(MODEL_FILE)
119
- return model, df
120
- return None, df
 
 
 
 
 
 
 
 
 
 
121
 
122
- # Initial training on startup
123
  print("Starting WinGo 3-Minute Predictor...")
124
- model, df = load_and_train()
 
 
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 = get_current_period()
130
  return f"⏳ Live period {period}: Not enough data yet (need {SEQUENCE_LEN} records)"
131
- period = get_current_period()
132
  try:
133
- last10 = df['category'].tail(SEQUENCE_LEN).tolist()
134
- inp = np.array(last10).reshape(1, SEQUENCE_LEN, 1)
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 with auto‑refresh every 30 seconds (no manual button)
143
  with gr.Blocks(title="WinGo 3-Minute Predictor") as demo:
144
- gr.Markdown("# 🎯 WinGo 3-Minute Game Predictor")
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