Team Ai
Apppublic

Soumyad2003/Code_Explainer

sourceHugging Faceupdated 1y agoView on Hugging Face
1likes
app.py77 linesDownload Raw Back to root
1import os2import streamlit as st3import google.generativeai as genai4from dotenv import load_dotenv5 6load_dotenv()7 8api_key = os.getenv('GENAI_API_KEY')9 10genai.configure(api_key=api_key)11 12# Define the completion function13 14 15def get_completion(code_snippet):16    python_code_examples = f"""17    ---------------------18    Example 1: Code Snippet19    x = 1020    def foo():21        global x22        x = 523    foo()24    print(x)25    Correct output: 526    Code Explanation: Inside the foo function, the global keyword is used to modify the global variable x to be 5.27    So, print(x) outside the function prints the modified value, which is 5.28    ---------------------29    Example 2: Code Snippet30    def modify_list(input_list):31        input_list.append(4)32        input_list = [1, 2, 3]33    my_list = [0]34    modify_list(my_list)35    print(my_list)36    Correct output: [0, 4]37    Code Explanation: Inside the modify_list function, an element 4 is appended to input_list.38    Then, input_list is reassigned to a new list [1, 2, 3], but this change doesn't affect the original list.39    So, print(my_list) outputs [0, 4].40    ---------------------41    """42 43    prompt = f"""44    Your task is to act as a Python Code Explainer.45    I'll give you a Code Snippet.46    Your job is to explain the Code Snippet step-by-step.47    Break down the code into as many steps as possible.48    Share intermediate checkpoints & steps along with results.49    Few good examples of Python code output between #### separator:50    ####51    {python_code_examples}52    ####53    Code Snippet is shared below, delimited with triple backticks:54    ```55    {code_snippet}56    ```57    """58 59    model = genai.GenerativeModel(model_name='gemini-1.5-flash')60    response = model.generate_content(prompt, generation_config={'max_output_tokens': 5000, 'temperature': 0})61    return response.text62 63# Streamlit interface64 65 66st.title("Code Explainer")67 68code_snippet = st.text_area("Enter your code snippet here:", height=200)69 70if st.button("Explain Code"):71    if code_snippet:72        explanation = get_completion(code_snippet)73        st.write("### Explanation:")74        st.write(explanation)75    else:76        st.write("Please enter a code snippet.")77