import streamlit as st import pandas as pd import numpy as np import plotly.express as px # --- Core Binary Logic --- def to_7bit_binary(number): """Converts a number (1-90) to a 7-bit binary string (e.g., 5 -> '0000101')""" # format(number, '07b') pads with zeros up to 7 characters return format(number, '07b') def from_7bit_binary(binary_str): """Converts a 7-bit binary string back to an integer""" return int(binary_str, 2) def drawing_to_binary_matrix(drawing): """Converts a list of 5 numbers into a 5x7 matrix of 0s and 1s (integers)""" matrix = [] for num in drawing: bin_str = to_7bit_binary(num) matrix.append([int(b) for b in bin_str]) return matrix # --- Prediction Logic --- def predict_next_binary_drawing(history_matrices, mode="Frequenza di Bit"): """ Given a history of 5x7 matrices, predicts the next 5x7 matrix (and thus 5 numbers). We treat each of the 5 positions as an independent 7-bit stream. """ predicted_drawing = [] # We predict position by position (Estratto 1, Estratto 2... Estratto 5) for pos in range(5): predicted_bits = "" # We predict bit by bit (Bit 0 to Bit 6) for bit_idx in range(7): # Extract the history of THIS specific bit in THIS specific position # history_matrices is ordered Newest[0] -> Oldest[N] bit_history = [matrix[pos][bit_idx] for matrix in history_matrices] if mode == "Trend a Breve Termine": # Look only at the last 10 drawings (indices 0 to 9) recent_history = bit_history[:10] ones_count = sum(recent_history) zeros_count = len(recent_history) - ones_count predicted_bits += "1" if ones_count >= zeros_count else "0" elif mode == "Inversione (Ritardo del Bit)": # If the bit has been 1 for a long time, bet on 0 (and vice-versa) # Count how many times the most recent state has repeated consecutively current_state = bit_history[0] consecutive = 0 for state in bit_history: if state == current_state: consecutive += 1 else: break # If it repeated >= 3 times, bet on the inversion if consecutive >= 3: predicted_bits += "0" if current_state == 1 else "1" else: # Otherwise expect continuity predicted_bits += str(current_state) # Convert the predicted 7-bit string back to a number predicted_number = from_7bit_binary(predicted_bits) # --- Safety constraints for Lotto (1-90) --- # 7 bits can encode 0-127. If the model predicts 0 or >90, we must adjust. # This is the "noise" of raw binary prediction in a constrained system. if predicted_number == 0: predicted_number = 1 elif predicted_number > 90: # Simple modulus folding to keep it in range (e.g. 91 becomes 1) predicted_number = (predicted_number % 90) if predicted_number == 0: predicted_number = 90 # Ensure no duplicates in the drawing while predicted_number in predicted_drawing: predicted_number += 1 if predicted_number > 90: predicted_number = 1 predicted_drawing.append(predicted_number) return predicted_drawing # --- Streamlit UI --- def run_binary_module(data, selected_wheel, focus_numbers=None): st.subheader(f"🔢 Analisi Binaria a 7-Bit - Ruota {selected_wheel}") st.markdown("Approccio IA che scompone i 90 numeri in codice binario (matrici di Zeri e Uni) per cercare pattern invisibili all'uomo.") if not data or len(data) < 20: st.warning("Dati insufficienti per l'analisi binaria.") return # 1. Show the transformation concept st.markdown("#### 1. La Traduzione Binaria (Ultime 3 Estrazioni)") st.info("I numeri (da 1 a 90) vengono convertiti in 7 bit. Esempio: il numero 5 diventa `0000101`. Un'estrazione intera diventa una griglia.") cols = st.columns(3) for i in range(3): with cols[i]: drawing = data[i] st.markdown(f"**Estrazione -{i}**\n\n({', '.join(map(str, drawing))})") # Create a visual matrix bin_matrix = drawing_to_binary_matrix(drawing) df_vis = pd.DataFrame(bin_matrix, columns=['B6 (64)', 'B5 (32)', 'B4 (16)', 'B3 (8)', 'B2 (4)', 'B1 (2)', 'B0 (1)'], index=[f"{drawing[0]}", f"{drawing[1]}", f"{drawing[2]}", f"{drawing[3]}", f"{drawing[4]}"]) # Simple heatmap for visualization fig = px.imshow(df_vis, text_auto=True, aspect="auto", color_continuous_scale="greys", title=f"Matrice {i}") fig.update_layout(coloraxis_showscale=False, margin=dict(l=0, r=0, b=0, t=30)) st.plotly_chart(fig, width="stretch") st.divider() # 2. Prediction Engine st.markdown("#### 2. Motore Predittivo Binario") # Convert all history to matrices with st.spinner("Compilazione archivio in matrici n-dimensionali..."): history_matrices = [drawing_to_binary_matrix(d) for d in data] col_mode, col_btn = st.columns([2, 1]) with col_mode: pred_mode = st.selectbox("Modalità Logica del Modello", [ "Trend a Breve Termine", "Inversione (Ritardo del Bit)" ]) with col_btn: st.write("") # Spacing st.write("") run_pred = st.button("🧠 Genera Cinquina Binaria", width="stretch") if run_pred: with st.spinner("Analisi stream di bit in corso..."): predicted_nums = predict_next_binary_drawing(history_matrices, mode=pred_mode) st.success("Predizione completata!") # UI Display p_cols = st.columns(5) for i, num in enumerate(predicted_nums): with p_cols[i]: bin_repr = to_7bit_binary(num) # Highlight if not in focus border_color = "#444" text_color = "#00ff00" if focus_numbers and num not in focus_numbers: border_color = "#ff4b4b" text_color = "#888" st.markdown(f"""