Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import CodeT5ForConditionalGeneration, CodeT5Tokenizer
|
| 4 |
+
|
| 5 |
+
# Load pre-trained CodeT5 model and tokenizer
|
| 6 |
+
model = CodeT5ForConditionalGeneration.from_pretrained("Salesforce/code-t5-small")
|
| 7 |
+
tokenizer = CodeT5Tokenizer.from_pretrained("Salesforce/code-t5-small")
|
| 8 |
+
|
| 9 |
+
def generate_code(prompt, code_file):
|
| 10 |
+
# Read uploaded code file
|
| 11 |
+
if code_file:
|
| 12 |
+
code_text = code_file.read().decode("utf-8")
|
| 13 |
+
else:
|
| 14 |
+
code_text = ""
|
| 15 |
+
|
| 16 |
+
# Tokenize input prompt
|
| 17 |
+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
|
| 18 |
+
|
| 19 |
+
# Generate code using CodeT5 model
|
| 20 |
+
output = model.generate(input_ids=input_ids, max_length=256)
|
| 21 |
+
generated_code = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 22 |
+
|
| 23 |
+
# Return generated code and code preview
|
| 24 |
+
return generated_code, f"```python\n{generated_code}\n```"
|
| 25 |
+
|
| 26 |
+
# Create Gradio interface
|
| 27 |
+
iface = gr.Interface(
|
| 28 |
+
fn=generate_code,
|
| 29 |
+
inputs=[
|
| 30 |
+
________gr.Textbox(label="Input_Prompt",_placeholder="Enter_a_prompt"),
|
| 31 |
+
________gr.Upload(label="Upload_Code_File",_file_types=["py"])
|
| 32 |
+
],
|
| 33 |
+
outputs=[
|
| 34 |
+
________gr.Textbox(label="Generated_Code"),
|
| 35 |
+
________gr.Code(label="Code_Preview",_language="python")
|
| 36 |
+
____],
|
| 37 |
+
title="Code Generation with CodeT5",
|
| 38 |
+
description="Generate Python code based on input prompt and uploaded code file."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Launch Gradio interface
|
| 42 |
+
iface.launch()
|