File size: 7,934 Bytes
2202957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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"""

                    <div style="text-align: center; background-color: #1e1e1e; color: {text_color}; padding: 15px; border-radius: 10px; border: 1px solid {border_color}; font-family: monospace;">

                        <span style="font-size: 0.8em; color: #888;">{bin_repr}</span>

                        <h2 style="margin: 5px 0;">{num}</h2>

                    </div>

                    """, unsafe_allow_html=True)
            
            if focus_numbers:
                out_of_focus = [n for n in predicted_nums if n not in focus_numbers]
                if out_of_focus:
                    st.warning(f"⚠️ Nota: I numeri {out_of_focus} non appartengono al gruppo focus attuale.")
                    
            st.markdown("---")
            st.markdown(f"**Logica Applicata:** `{pred_mode}`")
            st.caption("Il modello ha predetto indipendentemente lo stato futuro di ciascun singolo bit per ogni posizione estrazionale, e ha ricomposto i 7 bit risultanti nei numeri decimali finali (applicando un arrotondamento nel caso estremo in cui il binario generasse 0 o numeri > 90).")