CoolFace
Apppublic

usmannasir9989/Code-Explainer

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py47 linesDownload Raw Back to root
1import streamlit as st2import ast3import textwrap4 5st.set_page_config(page_title="Code Explainer", page_icon="๐Ÿ’ป", layout="wide")6 7st.title("๐Ÿ’ป Code Explainer App")8st.write("Paste your **Python code** below and get a simple explanation!")9 10code_input = st.text_area("Enter your Python code here:", height=200)11 12def explain_code(code):13    explanations = []14    try:15        tree = ast.parse(code)16        for node in ast.walk(tree):17            if isinstance(node, ast.Assign):18                targets = [t.id for t in node.targets if isinstance(t, ast.Name)]19                explanations.append(f"Variable **{', '.join(targets)}** is assigned a value.")20            elif isinstance(node, ast.For):21                explanations.append("This is a **for loop** iterating over a sequence.")22            elif isinstance(node, ast.While):23                explanations.append("This is a **while loop** that runs until a condition is False.")24            elif isinstance(node, ast.If):25                explanations.append("This is an **if statement** that checks a condition.")26            elif isinstance(node, ast.FunctionDef):27                explanations.append(f"A function named **{node.name}** is defined with parameters {', '.join([a.arg for a in node.args.args])}.")28            elif isinstance(node, ast.Return):29                explanations.append("This statement **returns a value** from a function.")30            elif isinstance(node, ast.Call):31                if isinstance(node.func, ast.Name):32                    explanations.append(f"The function **{node.func.id}()** is called.")33        if not explanations:34            explanations.append("Code parsed successfully, but no major structures found.")35    except Exception as e:36        explanations.append(f"โš ๏ธ Error parsing code: {e}")37    return explanations38 39if st.button("Explain Code"):40    if code_input.strip() == "":41        st.warning("โš ๏ธ Please enter some code first!")42    else:43        st.subheader("๐Ÿ“˜ Explanation:")44        explanations = explain_code(code_input)45        for exp in explanations:46            st.write("- " + exp)47