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(""" """, 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('", unsafe_allow_html=True) # Main Content st.markdown('

🔍 AI Receipe Generator

', unsafe_allow_html=True) # Image Upload Section col1, col2, col3 = st.columns([1, 2, 1]) with col2: st.markdown('
', 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('
', 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('
', 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('
', 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( """

Built with ❤️ using Streamlit and OpenAI GPT-4 Vision API

© 2024 Smart Image Analyzer

""", unsafe_allow_html=True ) if __name__ == "__main__": main()