CoolFace
Apppublic

mshaheer14/CodeExplainerBot

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py61 linesDownload Raw Back to root
1import os2import streamlit as st3import google.generativeai as genai4from dotenv import load_dotenv5 6# Load environment variables7load_dotenv()8 9# Configure Google API10GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")11genai.configure(api_key=GOOGLE_API_KEY)12model = genai.GenerativeModel('gemini-2.0-flash')13 14# Streamlit UI Configuration15st.set_page_config(page_title="Code Explainer Bot", page_icon="๐Ÿค–")16st.title("๐Ÿค– Code Explainer Bot")17st.caption("Paste your code and get line-by-line explanations!")18 19def generate_explanation(code):20    """Generate line-by-line code explanation using Gemini"""21    try:22        prompt = f"""23        Explain this code line by line in simple English. Format each explanation as:24        'Line [number]: [explanation]'25        26        Code:27        {code}28        """29        response = model.generate_content(prompt)30        return response.text31    except Exception as e:32        return f"Error generating explanation: {str(e)}"33 34# UI Elements35code_input = st.text_area("Paste your code here:", height=200, placeholder="// Your code here...")36 37if st.button("Explain Code"):38    if code_input.strip():39        with st.spinner("Analyzing code..."):40            explanation = generate_explanation(code_input)41            42            # Process and display explanations43            if "Line " in explanation:44                st.subheader("Code Explanation:")45                lines = explanation.split("\n")46                for line in lines:47                    if line.strip():48                        # Split on first colon only49                        parts = line.split(':', 1)50                        if len(parts) >= 2:51                            with st.expander(parts[0].strip()):52                                st.markdown(f"`{parts[1].strip()}`")53                        else:54                            st.markdown(f"`{line}`")55            else:56                st.warning(explanation)57    else:58        st.warning("Please enter some code to explain.")59 60st.markdown("---")61st.markdown("*Built with Google Gemini and Streamlit*")