sandeepUndurthi/code-explainer-gpt3.5
0
1import streamlit as st2import openai3import os4 5st.set_page_config(page_title="GPT Code Explainer", layout="centered")6st.title("🧠 GPT-3.5 Code Explainer")7st.write("Paste your Python code below and get a detailed explanation using OpenAI GPT-3.5.")8 9code_input = st.text_area("Paste Python Code", height=200)10 11# ✅ Use correct client for openai>=1.0.012api_key = os.getenv("OPENAI_API_KEY")13client = openai.Client(api_key=api_key) if api_key else None14 15if st.button("Explain"):16 if not client:17 st.error("❌ OPENAI_API_KEY not set. Add it as a secret in your Hugging Face Space.")18 elif code_input.strip():19 with st.spinner("Asking GPT-3.5..."):20 try:21 prompt = f"Explain the following Python function step-by-step:\n\n{code_input.strip()}"22 response = client.chat.completions.create(23 model="gpt-3.5-turbo",24 messages=[{"role": "user", "content": prompt}],25 max_tokens=512,26 temperature=0.5,27 )28 explanation = response.choices[0].message.content.strip()29 st.subheader("✅ Explanation")30 st.write(explanation)31 except Exception as e:32 st.error(f"OpenAI API error: {e}")33 else:34 st.warning("Please paste some code to explain.")35 