Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
2 |
+
import torch
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
# Load model and tokenizer from Hugging Face
|
6 |
+
model_name = "Salesforce/codegen-350M-multi"
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
8 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
9 |
+
|
10 |
+
# Set device (GPU if available)
|
11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
12 |
+
model.to(device)
|
13 |
+
|
14 |
+
def generate_code(prompt, max_length=100):
|
15 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
16 |
+
outputs = model.generate(
|
17 |
+
**inputs,
|
18 |
+
max_length=len(inputs["input_ids"][0]) + max_length,
|
19 |
+
temperature=0.7,
|
20 |
+
do_sample=True,
|
21 |
+
top_p=0.95,
|
22 |
+
pad_token_id=tokenizer.eos_token_id
|
23 |
+
)
|
24 |
+
generated_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
25 |
+
return generated_code
|
26 |
+
|
27 |
+
# Gradio Interface
|
28 |
+
interface = gr.Interface(
|
29 |
+
fn=generate_code,
|
30 |
+
inputs=[
|
31 |
+
gr.Textbox(lines=5, label="Code Prompt"),
|
32 |
+
gr.Slider(20, 300, step=10, label="Max Tokens", value=100),
|
33 |
+
],
|
34 |
+
outputs=gr.Textbox(label="Generated Code"),
|
35 |
+
title="🧠 Code Generator using HuggingFace",
|
36 |
+
description="Enter a prompt like `def factorial(n):` and let the AI complete the code."
|
37 |
+
)
|
38 |
+
|
39 |
+
if __name__ == "__main__":
|
40 |
+
interface.launch()
|