nniehaus's picture
Update app.py
0e7d465 verified
import openai
import streamlit as st
from tenacity import retry, stop_after_attempt, wait_fixed
# Assuming the OpenAI API key is stored in Streamlit's secrets
openai.api_key = st.secrets["YOUR_OPENAI_API_KEY"]
st.title("Website Feature Code Generator")
# User inputs for the feature they want to add
feature_description = st.text_area(
"Describe the website feature you'd like to implement:",
placeholder="E.g., A contact form with name, email, and message fields that emails the site owner."
)
@retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
def call_openai_api(feature_description):
try:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful AI trained in web development."},
{"role": "user", "content": feature_description}
],
)
# Prepare a prompt that asks for structured code with clear instructions
prompt = f"Generate structured code (HTML, CSS, JavaScript) for the website feature described: '{feature_description}'. " \
"Include comments to guide someone on where to place each part of the code in their website."
return response.choices[0].message['content']
except Exception as e:
st.error(f"An error occurred: {str(e)}")
return None
if st.button("Generate Code"):
code = call_openai_api(feature_description)
if code:
# Display the generated code with instructions
st.subheader("Generated Code and Instructions")
st.text(code)
st.markdown("""
**Instructions:**
- Copy the **HTML** section and paste it into the body of your HTML file where you want the feature to appear.
- Copy the **CSS** section and paste it into your CSS file or within the `<style>` tag in the `<head>` section of your HTML.
- Copy the **JavaScript** section and paste it before the closing `</body>` tag of your HTML, preferably in a separate JavaScript file linked to your HTML.
""")
else:
st.write("Could not generate the code. Please check the feature description and try again.")