File size: 2,168 Bytes
f7093ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM

# Available models for code explanation
MODELS = {
    "CodeT5-small-sum": "Salesforce/codet5-small",
    "CodeT5-base-sum": "Salesforce/codet5-base-multi-sum",
    "CodeBERTa": "huggingface/CodeBERTa-small-v1"
}

def load_model(model_name):
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
    # Use summarization for CodeT5, text2text-generation for others
    if "codet5" in model_name.lower():
        return pipeline("summarization", model=model, tokenizer=tokenizer)
    else:
        return pipeline("text2text-generation", model=model, tokenizer=tokenizer)

def explain_code(code, model_choice):
    model_id = MODELS[model_choice]
    explainer = load_model(model_id)
    lines = code.splitlines()
    line_explanations = []
    for idx, line in enumerate(lines):
        if not line.strip():
            continue  # Skip empty lines
        input_length = len(line.split())
        max_length = max(1, input_length // 2)
        gen_kwargs = dict(max_length=max_length, do_sample=False)
        if "codet5" in model_id.lower():
            result = explainer(line, **gen_kwargs)[0].get('summary_text', '')
        else:
            prompt = f"Explain this line of code:\n{line}"
            result = explainer(prompt, **gen_kwargs)[0].get('generated_text', '')
        line_explanations.append(f"Line {idx+1}: {line}\nExplanation: {result.strip()}\n")
    return "\n".join(line_explanations)

def main():
    with gr.Blocks() as demo:
        gr.Markdown("# CodeExplainerBot (Hugging Face UI)")
        model_choice = gr.Dropdown(list(MODELS.keys()), label="Select a model", value="CodeT5-small-sum")
        code_input = gr.Textbox(label="Paste your code here", lines=20)
        output = gr.Textbox(label="Line-by-line Explanation", lines=20)
        explain_btn = gr.Button("Explain Code")
        explain_btn.click(fn=explain_code, inputs=[code_input, model_choice], outputs=output)
    demo.launch()

if __name__ == "__main__":
    main()