File size: 1,433 Bytes
0c96f74
ed47303
0c96f74
5a3467a
 
 
 
 
 
 
0c96f74
ed47303
5a3467a
ed47303
 
 
 
8fedf42
 
 
 
 
 
 
 
 
5a3467a
 
 
 
 
 
 
 
 
 
8fedf42
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import gradio as gr
from transformers import pipeline

# Use a model tuned for reasoning and instruction following
pipe = pipeline(
    "text-generation",
    model="microsoft/Phi-3-mini-4k-instruct",
    device=-1,          # <-- forces CPU
    max_new_tokens=300
)

def explain_code(code, level):
    prompt = f"Explain clearly what the following {level.lower()} code does:\n\n{code}\n\nExplanation:"
    result = pipe(prompt)[0]["generated_text"]
    explanation = result[len(prompt):].strip()
    return explanation

def update_language(level):
    lang_map = {
        "Python": "python",
        "C": "c",
        "JavaScript": "javascript",
        "Other": "text"
    }
    return gr.update(language=lang_map.get(level, "text"))

custom_css = """
div.svelte-1ipelgc, div.ace_content, .ace_editor {
    cursor: text !important;
}
.ace_editor {
    pointer-events: auto !important;
}
"""

with gr.Blocks(css=custom_css, title="💡 Code Explainer") as demo:
    gr.Markdown("### Enter code and get a natural language explanation.")

    lang = gr.Radio(["Python", "C", "JavaScript", "Other"], value="Python", label="Language")
    code = gr.Code(language="python", label="Code", lines=12)
    output = gr.Textbox(label="Explanation", lines=8)

    lang.change(fn=update_language, inputs=lang, outputs=code)
    btn = gr.Button("Explain Code")

    btn.click(fn=explain_code, inputs=[code, lang], outputs=output)

demo.launch()