Spaces:
Sleeping
Sleeping
| 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.") | |