chmawia/CodeMagic
0
1import os2import streamlit as st3from transformers import AutoModelForSeq2SeqLM, AutoTokenizer4import torch5import subprocess6 7# Force CPU usage & prevent model download issues8os.environ["HF_HOME"] = "./cache" # Store model locally9MODEL_NAME = "Salesforce/codegen-350M-mono" # Updated model10 11tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)12model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)13 14def generate_code(description, language):15 prompt = f"Generate {language} code: {description}"16 inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True)17 outputs = model.generate(**inputs, max_length=400)18 response = tokenizer.decode(outputs[0], skip_special_tokens=True)19 return response.strip()20 21def execute_code(code, language):22 if language == "Python":23 try:24 result = subprocess.run(['python3', '-c', code], capture_output=True, text=True, timeout=5)25 return result.stdout if result.stdout else result.stderr26 except Exception as e:27 return str(e)28 return "Code execution only supported for Python."29 30# Streamlit UI31st.title("Multi-Language Text-to-Code AI")32st.write("Convert natural language descriptions into code in different programming languages! Run Python code directly in the app.")33 34description = st.text_area("Describe your coding task...")35language = st.selectbox("Select Programming Language", ["Python", "JavaScript", "Java"])36 37if st.button("Generate Code"):38 if description:39 code = generate_code(description, language)40 st.code(code, language=language.lower())41 42 if language == "Python":43 output = execute_code(code, language)44 st.text_area("Execution Output", output, height=150)45 else:46 st.warning("Please enter a description to generate code.")47 