Spaces:
Sleeping
Sleeping
File size: 12,558 Bytes
246f244 | 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 | # streamlit_app.py
import streamlit as st
import pandas as pd
from pathlib import Path
import re
import json
from collections import Counter
# Import V3.0 backend
from lotto_predictor import (
predict_for_game_v3,
GAME_CONFIGS,
NumpyEncoder,
clean_powerball_df,
load_csv_for_game
)
# Data paths (adjust if your files live in a data/ subfolder)
DATA_PATHS = {
"G5 (Gimme 5)": "gimme5_results.csv",
"LA (Lotto America)": "la_results.csv",
"MB (Megabucks)": "mb_results.csv",
"MM (Mega Millions)": "mm_results.csv",
"PB (Powerball)": "pb_results.csv",
"wheel_template": "wheel.txt",
}
st.set_page_config(page_title="Multi Lotto AI Engine V3.0", layout="centered")
st.title("π― Lotto AI Engine (V3.0)")
# -------------------------
# Helper functions for V3.0
# -------------------------
def get_hot_and_cold_numbers(df: pd.DataFrame, cfg, top_n: int = 10):
"""Calculate hot and cold numbers from the dataframe"""
# Count frequency of each number across all main columns
all_numbers = []
for col in cfg.main_cols:
all_numbers.extend(df[col].astype(int).tolist())
freq_counter = Counter(all_numbers)
# Get all possible numbers for this game
all_possible = list(range(cfg.main_min, cfg.main_max + 1))
# Create frequency list with zeros for missing numbers
freq_list = [(num, freq_counter.get(num, 0)) for num in all_possible]
# Sort by frequency
sorted_by_freq = sorted(freq_list, key=lambda x: x[1], reverse=True)
# Hot numbers (most frequent)
hot = sorted_by_freq[:top_n]
# Cold numbers (least frequent)
cold = sorted_by_freq[-top_n:]
cold.reverse() # Show coldest first
return hot, cold
@st.cache_data
def load_wheel_raw_text(path: str) -> str:
"""
Read wheel template as raw text using latin-1 fallback (robust to special bytes).
Returns empty string if missing or unreadable.
"""
p = Path(path)
if not p.exists():
return ""
try:
# latin-1 will never fail for single-byte encodings; errors='replace' for safety
text = p.read_text(encoding="latin-1", errors="replace")
return text
except Exception:
return ""
def select_20_wheel_numbers(hot: list, cold: list):
"""Select 20 numbers for wheeling using hot/cold analysis"""
wheel_map = {}
wheel_labels = list("ABCDEFGHIJKLMNOPQRST")
# Take top 10 hot numbers
hot_numbers = [num for num, freq in hot[:10]]
# Take bottom 10 cold numbers
cold_numbers = [num for num, freq in cold[:10]]
# Combine them
selected_numbers = hot_numbers + cold_numbers
# Map to letters A-T
for i, letter in enumerate(wheel_labels):
if i < len(selected_numbers):
wheel_map[letter] = selected_numbers[i]
return wheel_map
def convert_numeric_wheel_to_letter_template(raw_text: str, wheel_size: int = 20) -> str:
"""
Convert numeric wheel lines like:
1-01-02-06-18-19-46
into letter-template lines:
A B C D E
"""
if not raw_text:
return ""
lines = raw_text.splitlines()
out_lines = []
for line in lines:
# Detect lines that start with an index + dash (e.g. " 1-01-02-06-18-19-46")
if re.match(r'^\s*\d+\s*-', line):
# extract all integer tokens (1 or 2 digits)
nums = re.findall(r'\d{1,2}', line)
if not nums:
continue
# Many files start the line with the ticket index; drop it if present and equals first num
first_num_match = re.match(r'^\s*(\d+)', line)
if first_num_match and nums and nums[0] == first_num_match.group(1):
nums = nums[1:]
if len(nums) < 5:
# skip if fewer than 5 picks found
continue
picks = nums[:5] # take the first five numbers
letters = []
for n_str in picks:
n = int(n_str)
# Map 1->A, 2->B, ... wrap/clamp if needed
idx = (n - 1) % 26
letters.append(chr(ord('A') + idx))
if len(letters) >= 5:
out_lines.append(" ".join(letters))
return "\n".join(out_lines)
def expand_wheel_with_template(wheel_map: dict, template: str):
"""Expand wheel template into actual number combinations"""
combos = []
lines = template.strip().split('\n')
for line in lines:
letters = line.strip().split()
if len(letters) >= 5:
combo = []
for letter in letters[:5]: # Take first 5 letters
if letter in wheel_map:
combo.append(wheel_map[letter])
if len(combo) == 5:
combos.append(sorted(combo))
return combos
# -------------------------
# Display helpers
# -------------------------
def display_hot_cold_tables(hot_df: pd.DataFrame, cold_df: pd.DataFrame):
hot_df.index = range(1, len(hot_df) + 1)
hot_df.index.name = "No"
cold_df.index = range(1, len(cold_df) + 1)
cold_df.index.name = "No"
with st.expander("π₯ Hot Numbers (Top 10)"):
st.table(hot_df)
with st.expander("βοΈ Cold Numbers (Bottom 10)"):
st.table(cold_df)
def display_wheel_table_from_hotcold(hot_df: pd.DataFrame, cold_df: pd.DataFrame):
"""
Build the 20-number wheel mapping and show the table in the UI.
Returns wheel_map (dict letter->number).
"""
hot = [(int(n), f) for n, f in hot_df.values]
cold = [(int(n), f) for n, f in cold_df.values]
wheel_map = select_20_wheel_numbers(hot, cold)
wheel_labels = list("ABCDEFGHIJKLMNOPQRST")
ordered_numbers = [wheel_map.get(l, None) for l in wheel_labels]
wheel_df = pd.DataFrame([ordered_numbers], columns=wheel_labels)
with st.expander("π‘ Your 20 Numbers to Wheel"):
st.table(wheel_df)
return wheel_map
def display_wheel_combinations_from_raw(wheel_map: dict, raw_template_text: str):
"""
Convert numeric wheel template to letter-template, then expand and display combos.
"""
if not raw_template_text:
st.warning("Wheel template file is empty or not found.")
return
letter_template = convert_numeric_wheel_to_letter_template(raw_template_text)
if not letter_template:
st.warning("Wheel template parsing found no valid ticket lines.")
return
combos = expand_wheel_with_template(wheel_map, letter_template)
if not combos:
st.warning("No combinations produced after expansion.")
return
df = pd.DataFrame(combos, columns=["Num1", "Num2", "Num3", "Num4", "Num5"])
df.index = [f"Ticket{i+1}" for i in range(len(df))]
df.index.name = "No"
with st.expander(f"ποΈ Wheel Combinations ({len(df)} tickets)"):
st.dataframe(df)
# -------------------------
# UI & main logic
# -------------------------
lotto_options = [
"G5 (Gimme 5)",
"LA (Lotto America)",
"MB (Megabucks)",
"MM (Mega Millions)",
"PB (Powerball)",
]
lotto_type = st.selectbox("Select Lotto Type:", options=lotto_options, index=0)
# Map display names -> keys used in GAME_CONFIGS and predict_for_game_v3
GAME_KEY_MAP = {
"G5 (Gimme 5)": "gimme5",
"LA (Lotto America)": "la",
"MB (Megabucks)": "mb",
"MM (Mega Millions)": "mm",
"PB (Powerball)": "pb",
}
try:
game_key = GAME_KEY_MAP[lotto_type]
data_path = DATA_PATHS[lotto_type]
cfg = GAME_CONFIGS[game_key]
# Load dataset using V3.0 loader
df, _ = load_csv_for_game(Path(data_path), game_key)
# Hot/cold numbers computed using our helper
hot, cold = get_hot_and_cold_numbers(df, cfg)
hot_df = pd.DataFrame(hot, columns=["Number", "Frequency"])
cold_df = pd.DataFrame(cold, columns=["Number", "Frequency"])
# UI options - simplified for V3.0
run_backtest = st.checkbox("π§ͺ Run Backtest (slower but shows model performance)", value=False)
use_wheel = st.checkbox("π‘ Generate Wheel Combinations (if wheel.txt available)", value=False)
wheel_raw_text = load_wheel_raw_text(DATA_PATHS["wheel_template"]) if use_wheel else ""
# Styling
st.markdown(
"""
<style>
table { margin-left:auto; margin-right:auto; }
th, td { text-align:center !important; vertical-align: middle !important; }
</style>
""",
unsafe_allow_html=True,
)
if st.button("π° Generate Prediction" if not run_backtest else "π§ͺ Run Backtest"):
with st.spinner("Building ensemble models and generating results..."):
# Run V3.0 predictor
result = predict_for_game_v3(
csv_path=Path(data_path),
game_key=game_key,
run_backtest=run_backtest
)
if run_backtest:
# Display backtest results
if 'error' in result:
st.error(f"β Backtest Error: {result['error']}")
else:
st.success("β
Backtest Complete!")
# Show summary metrics
st.subheader("π Backtest Summary")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Model 3+ Matches", f"{result.get('model_3plus_rate', 0)}%")
with col2:
st.metric("Random 3+ Matches", f"{result.get('random_3plus_rate', 0)}%")
with col3:
st.metric("Even Count Accuracy", f"{result.get('even_count_accuracy', 0)}%")
# Detailed hit rates
st.subheader("π― Hit Rate Comparison")
hit_data = []
for i in range(6):
model_rate = result.get(f'model_hit_{i}_rate', 0)
random_rate = result.get(f'random_hit_{i}_rate', 0)
hit_data.append({
'Matches': i,
'Model Rate (%)': model_rate,
'Random Rate (%)': random_rate,
'Improvement': f"+{model_rate - random_rate:.1f}%" if model_rate > random_rate else f"{model_rate - random_rate:.1f}%"
})
hit_df = pd.DataFrame(hit_data)
st.table(hit_df)
# Raw results
with st.expander("π Full Backtest Results"):
st.json(result)
else:
# Display prediction results
st.success(f"π§ Predicted Numbers: {result['numbers']}")
if result.get("star") is not None:
star_col_name = cfg.star_col or 'Star'
st.success(f"π Predicted {star_col_name}: {result['star']}")
else:
st.info("βΉοΈ No bonus number for this game")
# Show additional info
st.info(f"π’ Total Sum: {sum(result['numbers'])} (Expected Range: {cfg.sum_min}β{cfg.sum_max})")
model_info = result.get('model_info', {})
st.info(f"π€ Models built for {model_info.get('numbers_modeled', 0)}/{model_info.get('total_possible', 0)} numbers")
# Show hot/cold tables
display_hot_cold_tables(hot_df, cold_df)
# Wheel (if requested)
if use_wheel and wheel_raw_text:
# Build and show wheel table (A..T mapping)
wheel_map = display_wheel_table_from_hotcold(hot_df, cold_df)
# Expand numeric wheel.txt to letter-template and display combos
display_wheel_combinations_from_raw(wheel_map, wheel_raw_text)
elif use_wheel:
st.warning("β οΈ Wheel template file (wheel.txt) not found or empty")
# Raw prediction results
with st.expander("π Full Prediction Details"):
st.json(result)
except FileNotFoundError:
st.error(f"β File not found: `{data_path}`")
except Exception as e:
st.error(f"β οΈ Error: {str(e)}")
import traceback
st.error(f"Details: {traceback.format_exc()}") |