Spaces:
Sleeping
Sleeping
File size: 1,366 Bytes
8559052 acb208c 9a1b6c8 acb208c 8559052 9a1b6c8 8559052 9a1b6c8 98146e0 9a1b6c8 8559052 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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.")
|