SandeepU commited on
Commit
9a1b6c8
·
verified ·
1 Parent(s): 18720af

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +12 -11
streamlit_app.py CHANGED
@@ -3,28 +3,29 @@ import openai
3
  import os
4
 
5
  st.set_page_config(page_title="GPT Code Explainer", layout="centered")
6
-
7
  st.title("🧠 GPT-3.5 Code Explainer")
8
  st.write("Paste your Python code below and get a detailed explanation using OpenAI GPT-3.5.")
9
 
10
  code_input = st.text_area("Paste Python Code", height=200)
11
 
12
- client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
13
 
14
  if st.button("Explain"):
15
- if not openai_api_key:
16
- st.error("OPENAI_API_KEY not set. Add it as a secret in your Hugging Face Space or local environment.")
17
  elif code_input.strip():
18
  with st.spinner("Asking GPT-3.5..."):
19
- prompt = f"Explain the following Python function step-by-step in plain English:\n\n{code_input.strip()}"
20
  try:
 
21
  response = client.chat.completions.create(
22
- model="gpt-3.5-turbo",
23
- messages=[{"role": "user", "content": prompt}],
24
- max_tokens=512,
25
- temperature=0.5,
26
- )
27
- explanation = response.choices[0].message["content"].strip()
28
  st.subheader("✅ Explanation")
29
  st.write(explanation)
30
  except Exception as e:
 
3
  import os
4
 
5
  st.set_page_config(page_title="GPT Code Explainer", layout="centered")
 
6
  st.title("🧠 GPT-3.5 Code Explainer")
7
  st.write("Paste your Python code below and get a detailed explanation using OpenAI GPT-3.5.")
8
 
9
  code_input = st.text_area("Paste Python Code", height=200)
10
 
11
+ # Create OpenAI client (v1.0+)
12
+ api_key = os.getenv("OPENAI_API_KEY")
13
+ client = openai.OpenAI(api_key=api_key) if api_key else None
14
 
15
  if 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: