import streamlit as st from transformers import AutoTokenizer, AutoModelForCausalLM from datetime import datetime # Custom CSS for UI st.markdown(""" """, unsafe_allow_html=True) # Cache model and tokenizer to avoid reloading @st.cache_resource def load_model_and_tokenizer(): checkpoint = "Salesforce/codegen-350M-mono" try: st.write("Loading tokenizer...") tokenizer = AutoTokenizer.from_pretrained(checkpoint) st.write("Loading model...") model = AutoModelForCausalLM.from_pretrained(checkpoint) st.write("Model and tokenizer loaded successfully!") return tokenizer, model except Exception as e: st.error(f"Failed to load model/tokenizer: {e}") return None, None # Load model and tokenizer once tokenizer, model = load_model_and_tokenizer() if tokenizer is None or model is None: st.stop() # Function to generate code def generate_code(description): prompt = f"Generate Python code for the following task: {description}\n" inputs = tokenizer(prompt, return_tensors="pt") try: outputs = model.generate( **inputs, max_length=500, num_return_sequences=1, pad_token_id=tokenizer.eos_token_id ) code = tokenizer.decode(outputs[0], skip_special_tokens=True) return code[len(prompt):].strip() except Exception as e: st.error(f"Error generating code: {e}") return "Error: Could not generate code." # Initialize chat history if "chat_history" not in st.session_state: st.session_state.chat_history = [] # UI Layout st.markdown('
Code Generation Bot
', unsafe_allow_html=True) st.markdown('
Describe your task, and I’ll generate Python code for you!
', unsafe_allow_html=True) with st.container(): # Input area description = st.text_area( "Enter your description here", placeholder="e.g., Write a function to calculate the factorial of a number", height=150 ) col1, col2 = st.columns([1, 1]) with col1: if st.button("Generate"): if description.strip(): with st.spinner("Thinking..."): generated_code = generate_code(description) st.session_state.chat_history.append({ "input": description, "output": generated_code, "time": datetime.now().strftime("%H:%M:%S") }) else: st.warning("Please enter a description first!") with col2: if st.button("Clear History"): st.session_state.chat_history = [] st.success("Chat history cleared!") # Display chat history if st.session_state.chat_history: st.write("### Chat History") for chat in st.session_state.chat_history: st.markdown(f'
You ({chat["time"]}): {chat["input"]}
', unsafe_allow_html=True) st.markdown(f'
{chat["output"]}
', unsafe_allow_html=True) st.markdown("---") st.info("Tip: Check the generated code for accuracy before using it!")