anas31 commited on
Commit
4854f4d
Β·
verified Β·
1 Parent(s): 8b9e03c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
2
+ import gradio as gr
3
+
4
+ # Load the model and tokenizer
5
+ tokenizer = AutoTokenizer.from_pretrained("sagard21/python-code-explainer")
6
+ model = AutoModelForSeq2SeqLM.from_pretrained("sagard21/python-code-explainer")
7
+
8
+ def explain_code(python_code):
9
+ # Tokenize the input code
10
+ inputs = tokenizer(python_code, return_tensors="pt", truncation=True, max_length=512)
11
+
12
+ # Generate explanation
13
+ explanation_ids = model.generate(
14
+ inputs["input_ids"],
15
+ max_length=256,
16
+ num_beams=5,
17
+ early_stopping=True
18
+ )
19
+
20
+ # Decode and return the explanation
21
+ explanation = tokenizer.decode(explanation_ids[0], skip_special_tokens=True)
22
+ return explanation
23
+
24
+ # Create the Gradio interface
25
+ demo = gr.Interface(
26
+ fn=explain_code,
27
+ inputs=gr.Code(
28
+ language="python",
29
+ label="Enter Python Code",
30
+ lines=10,
31
+ placeholder="def hello_world():\n print('Hello, world!')"
32
+ ),
33
+ outputs=gr.Textbox(
34
+ label="Code Explanation",
35
+ lines=5
36
+ ),
37
+ title="Python Code Explainer",
38
+ description="πŸ” Enter Python code and get a natural language explanation of what it does.",
39
+ examples=[
40
+ ["def add(a, b):\n return a + b"],
41
+ ["for i in range(5):\n print(i)"],
42
+ ["x = [i**2 for i in range(10) if i % 2 == 0]"]
43
+ ]
44
+ )
45
+
46
+ # Launch the app
47
+ demo.launch()