Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
|
4 |
+
# Load the model and tokenizer
|
5 |
+
try:
|
6 |
+
checkpoint = "Salesforce/codegen-350M-mono"
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
8 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint)
|
9 |
+
except Exception as e:
|
10 |
+
st.error(f"Error loading model: {e}")
|
11 |
+
st.stop()
|
12 |
+
|
13 |
+
# Function to generate code from description
|
14 |
+
def generate_code(description):
|
15 |
+
prompt = f"Generate Python code for the following task: {description}\n"
|
16 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
17 |
+
with st.spinner("Generating code..."):
|
18 |
+
outputs = model.generate(
|
19 |
+
**inputs,
|
20 |
+
max_length=500,
|
21 |
+
num_return_sequences=1,
|
22 |
+
pad_token_id=tokenizer.eos_token_id # Avoid padding token warnings
|
23 |
+
)
|
24 |
+
code = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
25 |
+
# Extract only the code part after the prompt
|
26 |
+
code = code[len(prompt):].strip()
|
27 |
+
return code
|
28 |
+
|
29 |
+
# Streamlit UI
|
30 |
+
st.title("Code Generation Bot")
|
31 |
+
st.write("Enter a description to generate Python code!")
|
32 |
+
|
33 |
+
description = st.text_area("Description", placeholder="e.g., Write a function to add two numbers")
|
34 |
+
if st.button("Generate Code"):
|
35 |
+
if description.strip():
|
36 |
+
generated_code = generate_code(description)
|
37 |
+
st.code(generated_code, language="python")
|
38 |
+
st.info("Tip: Review the code for accuracy before using!")
|
39 |
+
else:
|
40 |
+
st.warning("Please enter a description!")
|