DexterSptizu's picture
Update app.py
7699705 verified
import streamlit as st
import os
from openai import OpenAI
from PIL import Image
import io
import base64
st.set_page_config(
page_title="Your App",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
def apply_custom_css():
st.markdown("""
<style>
.stApp {
max-width: 1200px;
margin: 0 auto;
}
.upload-box {
border: 2px dashed #4CAF50;
border-radius: 10px;
padding: 20px;
text-align: center;
background-color: #f8f9fa;
}
.sidebar-content {
padding: 20px;
background-color: #f1f3f4;
border-radius: 10px;
}
.response-box {
background-color: #ffffff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.title-text {
color: #1E88E5;
text-align: center;
font-size: 2.5rem;
margin-bottom: 2rem;
}
</style>
""", unsafe_allow_html=True)
def initialize_session_state():
if 'history' not in st.session_state:
st.session_state.history = []
def encode_image_to_base64(image):
buffered = io.BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode('utf-8')
def analyze_image(image, question, api_key):
try:
client = OpenAI(api_key=api_key)
base64_image = encode_image_to_base64(image)
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": question},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{base64_image}"
}
},
],
}
],
max_tokens=500
)
return completion.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
def main():
apply_custom_css()
initialize_session_state()
# st.set_page_config(
# page_title="Smart Image Analyzer",
# page_icon="πŸ”",
# layout="wide"
# )
# Sidebar Configuration
with st.sidebar:
st.markdown('<div class="sidebar-content">', unsafe_allow_html=True)
st.image("https://your-logo-url.com/logo.png", width=100) # Add your logo
st.header("βš™οΈ Configuration")
api_key = st.text_input("OpenAI API Key:", type="password")
st.markdown("### 🎯 Quick Prompts")
quick_prompts = [
"Suggest receipe based on ingredients"
"Describe this image in detail",
"What objects are present?",
"Analyze the composition",
"Identify any text in the image",
]
selected_prompt = st.selectbox("Select a prompt:", quick_prompts)
st.markdown("</div>", unsafe_allow_html=True)
# Main Content
st.markdown('<h1 class="title-text">πŸ” AI Receipe Generator</h1>', unsafe_allow_html=True)
# Image Upload Section
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.markdown('<div class="upload-box">', unsafe_allow_html=True)
uploaded_file = st.file_uploader(
"Drop your image here or click to upload",
type=['png', 'jpg', 'jpeg'],
help="Supported formats: PNG, JPG, JPEG"
)
st.markdown('</div>', unsafe_allow_html=True)
if uploaded_file:
image = Image.open(uploaded_file)
# Image Display and Analysis Section
col1, col2 = st.columns([1, 1])
with col1:
st.image(image, use_container_width=True, caption="Uploaded Image")
with col2:
st.markdown('<div class="response-box">', unsafe_allow_html=True)
question = st.text_input(
"Your Question:",
value=selected_prompt,
key="question_input"
)
if st.button("πŸ” Analyze", use_container_width=True):
if not api_key:
st.error("⚠️ Please enter your OpenAI API key in the sidebar.")
else:
with st.spinner("πŸ”„ Analyzing your image..."):
response = analyze_image(image, question, api_key)
st.markdown("### πŸ“ Analysis Result:")
st.write(response)
# Add to history
st.session_state.history.append({
"question": question,
"response": response,
"timestamp": st.session_state.get("timestamp", "")
})
st.markdown('</div>', unsafe_allow_html=True)
# History Section
if st.session_state.history:
st.markdown("### πŸ“œ Previous Analyses")
for item in reversed(st.session_state.history[-5:]):
with st.expander(f"Q: {item['question'][:50]}..."):
st.write(item['response'])
# Footer
st.markdown("---")
st.markdown(
"""
<div style='text-align: center'>
<p>Built with ❀️ using Streamlit and OpenAI GPT-4 Vision API</p>
<p>Β© 2024 Smart Image Analyzer</p>
</div>
""",
unsafe_allow_html=True
)
if __name__ == "__main__":
main()