code-explainer-gpt35 / streamlit_app.py
SandeepU's picture
Upload 3 files
acb208c verified
Raw
History Blame Contribute Delete
1.37 kB
import streamlit as st
import openai
import os
st.set_page_config(page_title="GPT Code Explainer", layout="centered")
st.title("🧠 GPT-3.5 Code Explainer")
st.write("Paste your Python code below and get a detailed explanation using OpenAI GPT-3.5.")
code_input = st.text_area("Paste Python Code", height=200)
# βœ… Use correct client for openai>=1.0.0
api_key = os.getenv("OPENAI_API_KEY")
client = openai.Client(api_key=api_key) if api_key else None
if st.button("Explain"):
if not client:
st.error("❌ OPENAI_API_KEY not set. Add it as a secret in your Hugging Face Space.")
elif code_input.strip():
with st.spinner("Asking GPT-3.5..."):
try:
prompt = f"Explain the following Python function step-by-step:\n\n{code_input.strip()}"
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
max_tokens=512,
temperature=0.5,
)
explanation = response.choices[0].message.content.strip()
st.subheader("βœ… Explanation")
st.write(explanation)
except Exception as e:
st.error(f"OpenAI API error: {e}")
else:
st.warning("Please paste some code to explain.")