Spaces:
Sleeping
Sleeping
| 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() | |