# 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( """ """, 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()}")