CoolFace
Apppublic

Chethan4638/An_AI_Code_Reviewer

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py142 linesDownload Raw Back to root
1import streamlit as st2import google.generativeai as genai3import json4 5# Configure the API key from Streamlit secrets6# You must set up your Google AI API key in the Streamlit app's secrets.toml file.7# The key should be named 'GOOGLE_API_KEY'.8try:9    genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])10except KeyError:11    st.error("API Key not found. Please set 'GOOGLE_API_KEY' in your Streamlit secrets.")12    st.stop()13except Exception as e:14    st.error(f"An error occurred while configuring the API key: {e}")15    st.stop()16 17 18# Set up the model for code review.19# We'll use the gemini-1.5-pro model for its strong reasoning and coding capabilities.20model = genai.GenerativeModel("models/gemini-2.0-flash-exp")21 22def get_code_review(code_text):23    """24    Sends the user's code to the Google AI model for review.25    It prompts the model to act as a code reviewer and provide a bug report and fixed code.26    """27    if not code_text.strip():28        return None, None29        30    prompt = f"""31    You are an expert Python code reviewer. Your task is to analyze the provided Python code, identify any potential bugs, errors, or areas for improvement, and then provide a fixed, runnable version of the code.32 33    Your response must be a JSON object with two keys:34    - "bug_report": A string describing the bugs and improvements found.35    - "fixed_code": A string containing the complete, fixed version of the code.36 37    Make sure the fixed code is correctly formatted as a single Python code block.38    39    Here is the Python code to review:40    41    {code_text}42    """43    44    try:45        response = model.generate_content(prompt)46        47        # Parse the JSON response from the model48        try:49            # The model's response might contain markdown formatting, so we need to clean it.50            json_response_str = response.text.strip().replace("```json", "").replace("```", "")51            data = json.loads(json_response_str)52            bug_report = data.get("bug_report", "No bugs found.")53            fixed_code = data.get("fixed_code", "")54            return bug_report, fixed_code55        except json.JSONDecodeError:56            st.warning("Could not parse the AI's response. The model may have returned malformed JSON.")57            return "The AI's response could not be parsed. Please try a different code snippet.", None58 59    except Exception as e:60        st.error(f"An error occurred while calling the Google AI API: {e}")61        return None, None62 63# Streamlit UI layout64st.set_page_config(page_title="AI Code Reviewer", page_icon="๐Ÿ“")65 66st.markdown(67    """68    <style>69    .stApp {70        background-color: #262730;71    }72    .stButton>button {73        background-color: #4CAF50;74        color: white;75        padding: 10px 24px;76        border-radius: 8px;77        border: none;78        cursor: pointer;79        font-weight: bold;80    }81    .stButton>button:hover {82        background-color: #45a049;83    }84    .stTextArea label, .stCodeBlock {85        font-family: 'Courier New', Courier, monospace;86    }87    .stCodeBlock {88        background-color: #ffffff;89        border: 1px solid #e0e0e0;90        border-radius: 8px;91        padding: 1em;92        overflow-x: auto;93    }94    h1, h2, h3 {95        color: #333333;96    }97    </style>98    """,99    unsafe_allow_html=True100)101 102st.title("An AI Code Reviewer")103 104with st.expander("๐Ÿ“ About This App", expanded=False):105    st.markdown(106        """107        This application uses a Google AI model to review your Python code.108        Simply enter your code in the text area below and click "Generate" to get a bug report and a fixed version of your code.109        """110    )111 112user_code = st.text_area(113    "Enter your Python code here...",114    height=300,115    placeholder="""# Example: Find the largest number in a list116numbers = [1, 5, 2, 8, 3]117max_num = number[0]118for num in numbers:119    if num > max_num:120        max_num = num121print("The largest number is:", max_num)122"""123)124 125if st.button("Generate"):126    if user_code.strip() == "":127        st.warning("Please enter some code to review.")128    else:129        with st.spinner("Reviewing your code..."):130            bug_report, fixed_code = get_code_review(user_code)131 132        if bug_report is not None:133            st.subheader("Code Review")134            st.markdown("---")135 136            st.subheader("Bug Report")137            st.info(bug_report)138 139            if fixed_code:140                st.subheader("Fixed Code")141                st.code(fixed_code, language="python")142