Download src/streamlit_app.py from faiz3123/PPS: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/spaces/faiz3123/PPS/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/faiz3123/PPS/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/faiz3123/PPS/resolve/main/src/streamlit_app.py
12.9 kB
| 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() |