Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +50 -0
- requirements.txt +3 -0
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
| 3 |
+
|
| 4 |
+
# Available models for code explanation
|
| 5 |
+
MODELS = {
|
| 6 |
+
"CodeT5-small-sum": "Salesforce/codet5-small",
|
| 7 |
+
"CodeT5-base-sum": "Salesforce/codet5-base-multi-sum",
|
| 8 |
+
"CodeBERTa": "huggingface/CodeBERTa-small-v1"
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
def load_model(model_name):
|
| 12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 13 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
| 14 |
+
# Use summarization for CodeT5, text2text-generation for others
|
| 15 |
+
if "codet5" in model_name.lower():
|
| 16 |
+
return pipeline("summarization", model=model, tokenizer=tokenizer)
|
| 17 |
+
else:
|
| 18 |
+
return pipeline("text2text-generation", model=model, tokenizer=tokenizer)
|
| 19 |
+
|
| 20 |
+
def explain_code(code, model_choice):
|
| 21 |
+
model_id = MODELS[model_choice]
|
| 22 |
+
explainer = load_model(model_id)
|
| 23 |
+
lines = code.splitlines()
|
| 24 |
+
line_explanations = []
|
| 25 |
+
for idx, line in enumerate(lines):
|
| 26 |
+
if not line.strip():
|
| 27 |
+
continue # Skip empty lines
|
| 28 |
+
input_length = len(line.split())
|
| 29 |
+
max_length = max(1, input_length // 2)
|
| 30 |
+
gen_kwargs = dict(max_length=max_length, do_sample=False)
|
| 31 |
+
if "codet5" in model_id.lower():
|
| 32 |
+
result = explainer(line, **gen_kwargs)[0].get('summary_text', '')
|
| 33 |
+
else:
|
| 34 |
+
prompt = f"Explain this line of code:\n{line}"
|
| 35 |
+
result = explainer(prompt, **gen_kwargs)[0].get('generated_text', '')
|
| 36 |
+
line_explanations.append(f"Line {idx+1}: {line}\nExplanation: {result.strip()}\n")
|
| 37 |
+
return "\n".join(line_explanations)
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
with gr.Blocks() as demo:
|
| 41 |
+
gr.Markdown("# CodeExplainerBot (Hugging Face UI)")
|
| 42 |
+
model_choice = gr.Dropdown(list(MODELS.keys()), label="Select a model", value="CodeT5-small-sum")
|
| 43 |
+
code_input = gr.Textbox(label="Paste your code here", lines=20)
|
| 44 |
+
output = gr.Textbox(label="Line-by-line Explanation", lines=20)
|
| 45 |
+
explain_btn = gr.Button("Explain Code")
|
| 46 |
+
explain_btn.click(fn=explain_code, inputs=[code_input, model_choice], outputs=output)
|
| 47 |
+
demo.launch()
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
transformers
|
| 3 |
+
sentencepiece
|