import pandas as pd import re import streamlit as st from datetime import datetime def calculate_advanced_stability(all_wheel_data, formations, start_idx, end_idx, min_sorte, max_sorte): if not all_wheel_data or not formations: return [] sorte_names = {1: "Estratto", 2: "Ambo", 3: "Terno", 4: "Quaterna", 5: "Cinquina"} results = [] max_history = min(len(data) for data in all_wheel_data.values()) s_idx = max(0, start_idx) e_idx = min(max_history, end_idx) total_draws = e_idx - s_idx if total_draws <= 0: return [] for formation in formations: f_set = set(formation) hits_by_sorte = {s: 0 for s in range(min_sorte, max_sorte + 1)} current_delays = {s: 0 for s in range(min_sorte, max_sorte + 1)} found_first = {s: False for s in range(min_sorte, max_sorte + 1)} for i in range(s_idx, e_idx): combined_draw = set() for w in all_wheel_data: combined_draw.update(all_wheel_data[w][i]) num_hits = len(combined_draw.intersection(f_set)) for s in range(min_sorte, max_sorte + 1): if num_hits >= s: hits_by_sorte[s] += 1 if not found_first[s]: current_delays[s] = i - s_idx found_first[s] = True f_stats = { 'formazione': "-".join(map(str, sorted(formation))), 'count': len(formation) } for s in range(min_sorte, max_sorte + 1): name = sorte_names[s] f_stats[f'{name} %'] = (hits_by_sorte[s] / total_draws * 100) f_stats[f'Rit. {name}'] = current_delays[s] if found_first[s] else total_draws results.append(f_stats) return results def verify_bets(last_draws, text_input): city_map = { 'BA': 'BA', 'BARI': 'BA', 'CA': 'CA', 'CAGLIARI': 'CA', 'FI': 'FI', 'FIRENZE': 'FI', 'GE': 'GE', 'GENOVA': 'GE', 'MI': 'MI', 'MILANO': 'MI', 'NA': 'NA', 'NAPOLI': 'NA', 'PA': 'PA', 'PALERMO': 'PA', 'RO': 'RO', 'RM': 'RO', 'ROMA': 'RO', 'TO': 'TO', 'TORINO': 'TO', 'VE': 'VE', 'VENEZIA': 'VE', 'NZ': 'NZ', 'NAZ': 'NZ', 'NAZIONALE': 'NZ', 'TUT': 'ALL', 'TUTTE': 'ALL', 'ALL': 'ALL' } tokens = re.sub(r'[^a-zA-Z0-9\s]', ' ', text_input).upper().split() hit_tracker = {code: [] for code in last_draws.keys()} current_wheels = [] for token in tokens: if token in city_map: val = city_map[token] current_wheels = list(last_draws.keys()) if val == 'ALL' else [val] elif token.isdigit(): num = int(token) targets = current_wheels if current_wheels else list(last_draws.keys()) for wheel in targets: if wheel in last_draws and num in last_draws[wheel]: if num not in hit_tracker[wheel]: hit_tracker[wheel].append(num) results = [] for wheel, numbers in hit_tracker.items(): if numbers: count = len(numbers) labels = ["ESTRATTO", "AMBO", "TERNO", "QUATERNA", "CINQUINA"] label = labels[min(count-1, 4)] results.append({'wheel': wheel, 'label': label, 'numbers': numbers, 'count': count}) return results def render_wheel_grid(all_wheel_data, history_idx, matched_numbers_by_wheel=None): cols = st.columns(4) wheel_order = ['BA', 'CA', 'FI', 'GE', 'MI', 'NA', 'PA', 'RO', 'TO', 'VE', 'NZ'] for i, w_code in enumerate(wheel_order): with cols[i % 4]: if w_code in all_wheel_data and len(all_wheel_data[w_code]) > history_idx: nums = all_wheel_data[w_code][history_idx] matched = matched_numbers_by_wheel.get(w_code, []) if matched_numbers_by_wheel else [] # HTML for numbers, handling 0 as "abbuio" (hidden/dimmed) num_html = [] for n in nums: if n == 0: # "Abbuio" effect: empty circle or very dimmed num_html.append('
') else: bg = "linear-gradient(135deg, #22c55e, #16a34a)" if n in matched else "linear-gradient(145deg, #ffffff, #e2e8f0)" color = "white" if n in matched else "#0f172a" border = "1px solid #fff" if n in matched else "none" num_html.append(f'
{n}
') st.markdown(f"""
{w_code}
{' '.join(num_html)}
""", unsafe_allow_html=True) def run_jarvis_module(all_wheel_data, wheels_list, extraction_dates=None): st.markdown(""" """, unsafe_allow_html=True) st.header("🤖 Modulo Jarvis (Advanced Restoration)") tab_stab, tab_ver = st.tabs(["🔍 Stabilità Avanzata", "✅ Verifica Giocate"]) with tab_stab: st.subheader("Configurazione Analisi") col_file, col_opts = st.columns([1, 1]) with col_file: uploaded_file = st.file_uploader("Carica formazioni (.txt)", type=["txt"], key="stab_file") # Gestione session state per input manuale/file if "stab_text_input" not in st.session_state: st.session_state.stab_text_input = "1.4.9.11.13.16.17.23.25.26.30.40.42.49.55.58.59.61.67.68.73.77.81.83.85.86.88.89.90" if uploaded_file: st.session_state.stab_text_input = uploaded_file.read().decode('utf-8') manual_input = st.text_area("Oppure incolla qui", value=st.session_state.stab_text_input, height=100, key="stab_area") st.session_state.stab_text_input = manual_input formations = [] for line in manual_input.splitlines(): nums = [int(n) for n in re.findall(r'\d+', line) if 1 <= int(n) <= 90] if nums: formations.append(nums) with col_opts: max_h = min(len(d) for d in all_wheel_data.values()) if all_wheel_data else 10000 range_mode = st.radio("Range", ["Ultime N", "Range Pers."], horizontal=True) if range_mode == "Ultime N": n_draws = st.number_input("Estrazioni", 1, max_h, max_h) start_i, end_i = 0, n_draws else: start_i = st.number_input("Da indice", 0, max_h-1, 0) end_i = st.number_input("A indice", start_i+1, max_h, max_h) col_s1, col_s2 = st.columns(2) sorte_min = col_s1.selectbox("Min Sorte", [1, 2, 3, 4, 5], index=1) sorte_max = col_s2.selectbox("Max Sorte", [1, 2, 3, 4, 5], index=2) rs_threshold = st.slider("Filtro Stabilità %", 0, 100, 0) if st.button("🚀 Esegui Analisi"): if formations: results = calculate_advanced_stability(all_wheel_data, formations, start_i, end_i, sorte_min, sorte_max) if results: df = pd.DataFrame(results) sorte_key = f"{ {1:'Estratto', 2:'Ambo', 3:'Terno', 4:'Quaterna', 5:'Cinquina'}[sorte_min] } %" if rs_threshold > 0: df = df[df[sorte_key] >= rs_threshold] st.dataframe(df.style.background_gradient(subset=[c for c in df.columns if '%' in c], cmap='Blues'), width="stretch") with tab_ver: st.subheader("Verifica Giocate & Griglia Ruote") # --- SELETTORE STORICO CON DATE --- max_draws = min(len(d) for d in all_wheel_data.values()) if all_wheel_data else 1 # Formattazione label date def date_label(i): if extraction_dates and i < len(extraction_dates): return extraction_dates[i] return f"Indice {i}" hist_idx = st.select_slider( "Seleziona estrazione (Data o Indice)", options=list(range(max_draws)), format_func=date_label, value=0, help="Sposta il cursore per verificare giocate su date passate." ) col_v1, col_v2 = st.columns([2, 1]) with col_v2: auto_mode = st.checkbox("🔄 Verifica real-time (Auto)", value=True, key="auto_verify_v2") uploaded_ver_file = st.file_uploader("Carica file giocate (.txt)", type=["txt"], key="ver_file_v2") # Caricamento file txt nella text area file_content = "" if uploaded_ver_file: file_content = uploaded_ver_file.read().decode('utf-8') btn_verify = st.button("🎯 VERIFICA ORA", width="stretch", key="btn_ver_v2") st.caption("Scorciatoia: Premi fuori dal campo o CTRL+INVIO") with col_v1: if "bet_text_input" not in st.session_state: st.session_state.bet_text_input = "" if uploaded_ver_file: st.session_state.bet_text_input = uploaded_ver_file.read().decode('utf-8') bet_input = st.text_area("Incolla qui le giocate", value=st.session_state.bet_text_input, height=150, key="bet_area_v2") st.session_state.bet_text_input = bet_input # LOGICA VERIFICA vincite = [] matched_map = {} if bet_input and (auto_mode or btn_verify): target_draws = {w: all_wheel_data[w][hist_idx] for w in all_wheel_data if len(all_wheel_data[w]) > hist_idx} vincite = verify_bets(target_draws, bet_input) for v in vincite: matched_map[v['wheel']] = v['numbers'] if vincite: st.success(f"🎊 Rilevate {len(vincite)} vincite per {date_label(hist_idx)}!") # Design più compatto per risultati multipli cols_res = st.columns(min(len(vincite), 4)) for idx, v in enumerate(vincite): with cols_res[idx % 4]: color = "#3b82f6" if v['count'] == 1 else "#10b981" if v['count'] == 2 else "#8b5cf6" st.markdown(f"""
{v['label']}
{v['wheel']}
{", ".join(map(str, v['numbers']))}
""", unsafe_allow_html=True) elif bet_input: st.info(f"Nessuna vincita rilevata per {date_label(hist_idx)}.") st.divider() st.markdown(f"#### 🎰 Tabellone Estrazione: {date_label(hist_idx)}") render_wheel_grid(all_wheel_data, hist_idx, matched_map)