jk12p commited on
Commit
49b9e99
·
verified ·
1 Parent(s): 4eb6999

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -22
app.py CHANGED
@@ -1,27 +1,30 @@
1
- import streamlit as st
2
  from transformers import T5Tokenizer, T5ForConditionalGeneration
3
 
4
- @st.cache_resource
5
- def load_model():
6
- tokenizer = T5Tokenizer.from_pretrained("Salesforce/codet5-base")
7
- model = T5ForConditionalGeneration.from_pretrained("Salesforce/codet5-base")
8
- return tokenizer, model
9
 
10
- tokenizer, model = load_model()
 
 
 
 
 
 
 
 
 
 
11
 
12
- st.title("🧠 Code Explainer (CodeT5)")
13
- st.markdown("Paste code and get an explanation using the CodeT5 model from Hugging Face.")
 
 
 
 
 
 
 
14
 
15
- code_input = st.text_area("Paste your code here:", height=200)
16
-
17
- if st.button("Explain Code"):
18
- if code_input.strip() == "":
19
- st.warning("Please paste some code first.")
20
- else:
21
- with st.spinner("Generating explanation..."):
22
- input_text = f"summarize: {code_input.strip()}"
23
- input_ids = tokenizer.encode(input_text, return_tensors="pt", truncation=True, max_length=512)
24
- outputs = model.generate(input_ids, max_length=150, num_beams=4, early_stopping=True)
25
- summary = tokenizer.decode(outputs[0], skip_special_tokens=True)
26
- st.success("Explanation:")
27
- st.write(summary)
 
1
+ import gradio as gr
2
  from transformers import T5Tokenizer, T5ForConditionalGeneration
3
 
4
+ # Load CodeT5 model and tokenizer
5
+ tokenizer = T5Tokenizer.from_pretrained("Salesforce/codet5-base")
6
+ model = T5ForConditionalGeneration.from_pretrained("Salesforce/codet5-base")
 
 
7
 
8
+ # Function to explain code
9
+ def explain_code(code_snippet):
10
+ if not code_snippet.strip():
11
+ return "❗ Please enter some code."
12
+
13
+ input_text = f"summarize: {code_snippet.strip()}"
14
+ input_ids = tokenizer.encode(input_text, return_tensors="pt", truncation=True, max_length=512)
15
+ outputs = model.generate(input_ids, max_length=150, num_beams=4, early_stopping=True)
16
+ explanation = tokenizer.decode(outputs[0], skip_special_tokens=True)
17
+
18
+ return explanation
19
 
20
+ # Gradio Interface
21
+ demo = gr.Interface(
22
+ fn=explain_code,
23
+ inputs=gr.Textbox(lines=15, label="Paste your code here"),
24
+ outputs=gr.Textbox(label="Explanation"),
25
+ title="🧠 Code Explainer using Hugging Face",
26
+ description="This tool uses Salesforce's CodeT5 to convert your code into a human-readable explanation. Works on CPU!",
27
+ theme="default"
28
+ )
29
 
30
+ demo.launch()