Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
MODEL_NAME = "Qwen/Qwen2.5-Coder-1.5B-Instruct"
|
| 6 |
+
|
| 7 |
+
print("Loading model... (this may take a minute)")
|
| 8 |
+
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 10 |
+
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 12 |
+
MODEL_NAME,
|
| 13 |
+
torch_dtype=torch.float32,
|
| 14 |
+
device_map="cpu"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
print("Model loaded!")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def generate_code(prompt):
|
| 21 |
+
if not prompt.strip():
|
| 22 |
+
return "Please enter a prompt."
|
| 23 |
+
|
| 24 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 25 |
+
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
outputs = model.generate(
|
| 28 |
+
**inputs,
|
| 29 |
+
max_new_tokens=512,
|
| 30 |
+
temperature=0.2,
|
| 31 |
+
do_sample=True
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 35 |
+
|
| 36 |
+
# Remove the original prompt from output
|
| 37 |
+
if result.startswith(prompt):
|
| 38 |
+
result = result[len(prompt):]
|
| 39 |
+
|
| 40 |
+
return result.strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
with gr.Blocks() as demo:
|
| 44 |
+
gr.Markdown("# 💻 Local AI Code Generator (CPU)")
|
| 45 |
+
gr.Markdown("Runs fully locally on Hugging Face Space 🚀")
|
| 46 |
+
|
| 47 |
+
prompt = gr.Textbox(
|
| 48 |
+
label="Your Prompt",
|
| 49 |
+
placeholder="e.g. Create a Python calculator",
|
| 50 |
+
lines=4
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
btn = gr.Button("Generate")
|
| 54 |
+
|
| 55 |
+
output = gr.Code(
|
| 56 |
+
label="Generated Code",
|
| 57 |
+
language="python"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
btn.click(generate_code, inputs=prompt, outputs=output)
|
| 61 |
+
|
| 62 |
+
demo.launch()
|