Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 2 |
+
import gradio as gr
|
| 3 |
+
|
| 4 |
+
# Load the CodeGen model and tokenizer. This model has 2B parameters and is specialized for code generation:contentReference[oaicite:16]{index=16}.
|
| 5 |
+
# Note: Downloading and loading this model may be slow, and it may require a GPU for reasonable performance.
|
| 6 |
+
tokenizer = AutoTokenizer.from_pretrained("Salesforce/codegen-2B-mono")
|
| 7 |
+
model = AutoModelForCausalLM.from_pretrained("Salesforce/codegen-2B-mono")
|
| 8 |
+
|
| 9 |
+
# Define the code generation function.
|
| 10 |
+
def generate_code(prompt):
|
| 11 |
+
# Format the prompt as a comment, because CodeGen is trained to take a code-related prompt in comment form:contentReference[oaicite:17]{index=17}.
|
| 12 |
+
formatted_prompt = f"# {prompt}\n"
|
| 13 |
+
# Tokenize the prompt and get input IDs for the model
|
| 14 |
+
input_ids = tokenizer.encode(formatted_prompt, return_tensors="pt")
|
| 15 |
+
# Use the model to generate code. We set a limit on max_length for the output.
|
| 16 |
+
# We also use a low temperature (0.2) to make the output more deterministic and focused.
|
| 17 |
+
output_ids = model.generate(input_ids, max_length=256, num_beams=1, do_sample=True, temperature=0.2)
|
| 18 |
+
# Decode the generated tokens back into a string of code.
|
| 19 |
+
generated_code = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 20 |
+
return generated_code
|
| 21 |
+
|
| 22 |
+
# Set up Gradio interface with a textbox for the task description and a code output component.
|
| 23 |
+
input_desc = gr.Textbox(lines=2, label="Task Description", placeholder="Describe the code you need...")
|
| 24 |
+
output_code = gr.Code(language="python", label="Generated Code")
|
| 25 |
+
|
| 26 |
+
demo = gr.Interface(
|
| 27 |
+
fn=generate_code,
|
| 28 |
+
inputs=input_desc,
|
| 29 |
+
outputs=output_code,
|
| 30 |
+
title="💻 Code Generation Assistant (CodeGen-2B)",
|
| 31 |
+
description="**Description:** Provide a natural language description of a programming task, "
|
| 32 |
+
"and the model will generate Python code to accomplish the task. "
|
| 33 |
+
"Uses Salesforce's CodeGen-2B-mono model (2B parameters) for code generation."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
demo.launch()
|