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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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import streamlit as st
import google.generativeai as genai
import re

# Set up the page
st.set_page_config(
    page_title="Number System Conversion Tutor",
    page_icon="🔢",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Initialize Gemini API
def setup_gemini():
    if 'gemini_api_key' not in st.session_state:
        st.session_state.gemini_api_key = "AIzaSyCWxM6Ic9zs-hZiovnMU8a4UJko7ObqPqU"
    
    # You'll need to add your own API key
    api_key = st.sidebar.text_input("Enter your Gemini API Key:", type="password")
    if api_key:
        st.session_state.gemini_api_key = api_key
        try:
            genai.configure(api_key="AIzaSyCWxM6Ic9zs-hZiovnMU8a4UJko7ObqPqU")
            return True
        except Exception as e:
            st.sidebar.error(f"Error configuring Gemini: {e}")
            return False
    return False

# Sidebar with educational content
def sidebar_educational_content():
    st.sidebar.title("Number System Learning Hub")
    
    st.sidebar.header("Conversion Methods")
    
    conversion_method = st.sidebar.selectbox(
        "Select Conversion Type:",
        ["Decimal to Binary", "Decimal to Octal", "Decimal to Hexadecimal",
         "Binary to Decimal", "Binary to Octal", "Binary to Hexadecimal",
         "Octal to Decimal", "Octal to Binary", "Octal to Hexadecimal",
         "Hexadecimal to Decimal", "Hexadecimal to Binary", "Hexadecimal to Octal"]
    )
    
    if conversion_method:
        show_conversion_method(conversion_method)
    
    st.sidebar.header("Number System Basics")
    st.sidebar.markdown("""
    - **Binary (Base-2)**: Uses 0 and 1
    - **Octal (Base-8)**: Uses digits 0-7
    - **Decimal (Base-10)**: Uses digits 0-9 (our everyday system)
    - **Hexadecimal (Base-16)**: Uses digits 0-9 and A-F
    """)
    
    st.sidebar.header("Engineering Applications")
    st.sidebar.markdown("""
    - **Binary**: Fundamental to all digital systems and computers
    - **Octal**: Used in UNIX file permissions and digital displays
    - **Hexadecimal**: Used in memory addressing, color codes, and assembly programming
    """)

def show_conversion_method(method):
    methods = {
        "Decimal to Binary": """
        **Steps:**
        1. Divide the decimal number by 2
        2. Record the remainder
        3. Divide the quotient by 2 again
        4. Repeat until quotient is 0
        5. Binary number is the remainders read from bottom to top
        
        **Example:** Convert 13 to binary
        13 ÷ 2 = 6 remainder 1
        6 ÷ 2 = 3 remainder 0
        3 ÷ 2 = 1 remainder 1
        1 ÷ 2 = 0 remainder 1
        Binary: 1101
        """,
        
        "Decimal to Octal": """
        **Steps:**
        1. Divide the decimal number by 8
        2. Record the remainder
        3. Divide the quotient by 8 again
        4. Repeat until quotient is 0
        5. Octal number is the remainders read from bottom to top
        
        **Example:** Convert 95 to octal
        95 ÷ 8 = 11 remainder 7
        11 ÷ 8 = 1 remainder 3
        1 ÷ 8 = 0 remainder 1
        Octal: 137
        """,
        
        "Decimal to Hexadecimal": """
        **Steps:**
        1. Divide the decimal number by 16
        2. Record the remainder (10=A, 11=B, 12=C, 13=D, 14=E, 15=F)
        3. Divide the quotient by 16 again
        4. Repeat until quotient is 0
        5. Hexadecimal number is the remainders read from bottom to top
        
        **Example:** Convert 255 to hexadecimal
        255 ÷ 16 = 15 remainder 15 (F)
        15 ÷ 16 = 0 remainder 15 (F)
        Hexadecimal: FF
        """,
        
        "Binary to Decimal": """
        **Steps:**
        1. Write down the binary number
        2. List powers of 2 from right to left (starting with 2^0)
        3. Multiply each binary digit by its corresponding power of 2
        4. Sum all the values
        
        **Example:** Convert 1101 to decimal
        1*2³ + 1*2² + 0*2¹ + 1*2⁰ = 8 + 4 + 0 + 1 = 13
        """,
        
        "Binary to Octal": """
        **Steps:**
        1. Group binary digits into sets of three (from right to left)
        2. Add leading zeros if needed
        3. Convert each group to its octal equivalent
        
        **Example:** Convert 101110 to octal
        Group: 101 110 → 5 6 → Octal: 56
        """,
        
        "Binary to Hexadecimal": """
        **Steps:**
        1. Group binary digits into sets of four (from right to left)
        2. Add leading zeros if needed
        3. Convert each group to its hexadecimal equivalent
        
        **Example:** Convert 11010111 to hexadecimal
        Group: 1101 0111 → D 7 → Hexadecimal: D7
        """,
        
        "Octal to Decimal": """
        **Steps:**
        1. Write down the octal number
        2. List powers of 8 from right to left (starting with 8^0)
        3. Multiply each octal digit by its corresponding power of 8
        4. Sum all the values
        
        **Example:** Convert 137 to decimal
        1*8² + 3*8¹ + 7*8⁰ = 64 + 24 + 7 = 95
        """,
        
        "Octal to Binary": """
        **Steps:**
        1. Convert each octal digit to a 3-bit binary number
        2. Combine all the binary groups
        
        **Example:** Convert 56 to binary
        5 → 101, 6 → 110 → Binary: 101110
        """,
        
        "Octal to Hexadecimal": """
        **Steps:**
        1. Convert octal to binary first
        2. Then convert binary to hexadecimal
        
        **Example:** Convert 56 to hexadecimal
        56 (octal) → 101110 (binary) → 0010 1110 → 2 E → 2E
        """,
        
        "Hexadecimal to Decimal": """
        **Steps:**
        1. Write down the hexadecimal number
        2. List powers of 16 from right to left (starting with 16^0)
        3. Multiply each hex digit by its corresponding power of 16
        (A=10, B=11, C=12, D=13, E=14, F=15)
        4. Sum all the values
        
        **Example:** Convert 2E to decimal
        2*16¹ + 14*16⁰ = 32 + 14 = 46
        """,
        
        "Hexadecimal to Binary": """
        **Steps:**
        1. Convert each hex digit to a 4-bit binary number
        2. Combine all the binary groups
        
        **Example:** Convert 2E to binary
        2 → 0010, E (14) → 1110 → Binary: 00101110
        """,
        
        "Hexadecimal to Octal": """
        **Steps:**
        1. Convert hexadecimal to binary first
        2. Then convert binary to octal
        
        **Example:** Convert 2E to octal
        2E (hex) → 00101110 (binary) → 056 → Octal: 56
        """
    }
    
    st.sidebar.markdown(methods.get(method, "Select a conversion method to see details"))

# Base conversion functions
def convert_base(number, from_base, to_base):
    try:
        # First convert to decimal
        if from_base != 10:
            decimal_val = int(str(number), from_base)
        else:
            decimal_val = int(number)
        
        # Then convert from decimal to target base
        if to_base == 10:
            return str(decimal_val)
        elif to_base == 2:
            return bin(decimal_val)[2:]
        elif to_base == 8:
            return oct(decimal_val)[2:]
        elif to_base == 16:
            return hex(decimal_val)[2:].upper()
        else:
            # Custom base conversion for bases other than 2,8,10,16
            digits = []
            n = decimal_val
            if n == 0:
                return "0"
            while n:
                n, remainder = divmod(n, to_base)
                digits.append(str(remainder) if remainder < 10 else chr(55 + remainder))
            return ''.join(digits[::-1])
    except Exception as e:
        return f"Error: {str(e)}"

# Validate input based on base
def is_valid_number(number, base):
    if base == 2:
        pattern = r'^[01]+$'
    elif base == 8:
        pattern = r'^[0-7]+$'
    elif base == 10:
        pattern = r'^[0-9]+$'
    elif base == 16:
        pattern = r'^[0-9A-Fa-f]+$'
    else:
        pattern = r'^[0-9A-Za-z]+$'
    
    return re.match(pattern, number) is not None

# Main calculator function
def base_conversion_calculator():
    st.title("Number System Conversion Calculator")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.header("Input")
        number = st.text_input("Enter number to convert:", value="1010")
        
        col1a, col1b = st.columns(2)
        with col1a:
            from_base = st.selectbox("From base:", [2, 8, 10, 16, "Custom"], index=0)
        with col1b:
            if from_base == "Custom":
                custom_from = st.number_input("Custom from base:", min_value=2, max_value=36, value=2)
                from_base = custom_from
            else:
                custom_from = from_base
        
        col2a, col2b = st.columns(2)
        with col2a:
            to_base = st.selectbox("To base:", [2, 8, 10, 16, "Custom"], index=3)
        with col2b:
            if to_base == "Custom":
                custom_to = st.number_input("Custom to base:", min_value=2, max_value=36, value=16)
                to_base = custom_to
            else:
                custom_to = to_base
        
        if st.button("Convert"):
            if not number:
                st.error("Please enter a number to convert")
            elif not is_valid_number(number, from_base):
                st.error(f"Invalid number for base {from_base}")
            else:
                result = convert_base(number, from_base, to_base)
                st.session_state.conversion_result = result
    
    with col2:
        st.header("Result")
        if 'conversion_result' in st.session_state:
            st.success(f"{number} (base {from_base}) = {st.session_state.conversion_result} (base {to_base})")
        
        st.header("Step-by-Step Explanation")
        if 'conversion_result' in st.session_state and from_base != 10 and to_base != 10:
            # Show intermediate decimal conversion
            decimal_val = int(str(number), from_base)
            st.write(f"First, convert from base {from_base} to decimal:")
            st.write(f"{number} (base {from_base}) = {decimal_val} (base 10)")
            st.write(f"Then, convert from decimal to base {to_base}:")
            st.write(f"{decimal_val} (base 10) = {st.session_state.conversion_result} (base {to_base})")
        elif 'conversion_result' in st.session_state:
            st.info("Select different from/to bases to see step-by-step explanation")

# AI Tutor function
def ai_tutor():
    st.header("AI Tutor: Ask about Number Systems")
    
    if not st.session_state.gemini_api_key:
        st.warning("Please enter your Gemini API key in the sidebar to use the AI tutor")
        return
    
    # Initialize the model
    try:
        model = genai.GenerativeModel('gemini-2.0-flash')
    except Exception as e:
        st.error(f"Failed to initialize Gemini model: {e}")
        return
    
    # Initialize chat history
    if "chat_history" not in st.session_state:
        st.session_state.chat_history = []
    
    # Display chat history
    for message in st.session_state.chat_history:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])
    
    # Chat input
    prompt = st.chat_input("Ask a question about number systems...")
    if prompt:
        # Add user message to chat history
        st.session_state.chat_history.append({"role": "user", "content": prompt})
        
        # Display user message
        with st.chat_message("user"):
            st.markdown(prompt)
        
        # Create a focused prompt to keep the AI on topic
        focused_prompt = f"""
        You are a tutor specializing in number systems and base conversions. 
        Please answer the following question about binary, octal, decimal, hexadecimal, 
        or other numeral systems and their conversions. 
        If the question is not related to number systems, politely decline to answer.
        
        Question: {prompt}
        """
        
        # Get AI response
        try:
            response = model.generate_content(focused_prompt)
            ai_response = response.text
        except Exception as e:
            ai_response = f"Sorry, I encountered an error: {str(e)}"
        
        # Add AI response to chat history
        st.session_state.chat_history.append({"role": "assistant", "content": ai_response})
        
        # Display AI response
        with st.chat_message("assistant"):
            st.markdown(ai_response)

# Main app
def main():
    sidebar_educational_content()
    gemini_ready = setup_gemini()
    
    tab1, tab2 = st.tabs(["Conversion Calculator", "AI Tutor"])
    
    with tab1:
        base_conversion_calculator()
    
    with tab2:
        ai_tutor()

if __name__ == "__main__":
    main()