import os import streamlit as st import google.generativeai as genai from dotenv import load_dotenv # Load environment variables load_dotenv() # Configure Google API GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") genai.configure(api_key=GOOGLE_API_KEY) model = genai.GenerativeModel('gemini-2.0-flash') # Streamlit UI Configuration st.set_page_config(page_title="Code Explainer Bot", page_icon="🤖") st.title("🤖 Code Explainer Bot") st.caption("Paste your code and get line-by-line explanations!") def generate_explanation(code): """Generate line-by-line code explanation using Gemini""" try: prompt = f""" Explain this code line by line in simple English. Format each explanation as: 'Line [number]: [explanation]' Code: {code} """ response = model.generate_content(prompt) return response.text except Exception as e: return f"Error generating explanation: {str(e)}" # UI Elements code_input = st.text_area("Paste your code here:", height=200, placeholder="// Your code here...") if st.button("Explain Code"): if code_input.strip(): with st.spinner("Analyzing code..."): explanation = generate_explanation(code_input) # Process and display explanations if "Line " in explanation: st.subheader("Code Explanation:") lines = explanation.split("\n") for line in lines: if line.strip(): # Split on first colon only parts = line.split(':', 1) if len(parts) >= 2: with st.expander(parts[0].strip()): st.markdown(f"`{parts[1].strip()}`") else: st.markdown(f"`{line}`") else: st.warning(explanation) else: st.warning("Please enter some code to explain.") st.markdown("---") st.markdown("*Built with Google Gemini and Streamlit*")