File size: 8,714 Bytes
af2bcb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ceb324
 
 
 
 
 
af2bcb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import streamlit as st
import os
from PIL import Image
import base64
from io import BytesIO
from utils.ai_analyzer import analyze_shelf_image
from utils.recommendations import generate_recommendations
from utils.ui_components import display_results, display_recommendations

st.set_page_config(
    page_title="Shelf Photo Analyzer",
    page_icon="🏪",
    layout="wide",
    initial_sidebar_state="collapsed"
)

st.markdown("""
<style>
    .main-header {
        font-size: 3rem;
        color: #FF6B6B;
        text-align: center;
        margin-bottom: 1rem;
    }
    .subtitle {
        font-size: 1.2rem;
        text-align: center;
        color: #666;
        margin-bottom: 2rem;
    }
    .upload-section {
        border: 2px dashed #FF6B6B;
        border-radius: 10px;
        padding: 2rem;
        text-align: center;
        margin: 1rem 0;
    }
    .results-container {
        background-color: #f8f9fa;
        border-radius: 10px;
        padding: 1.5rem;
        margin: 1rem 0;
    }
</style>
""", unsafe_allow_html=True)

def main():
    st.markdown('<h1 class="main-header">🏪 Shelf Photo Analyzer</h1>', unsafe_allow_html=True)
    st.markdown('<p class="subtitle">Błyskawiczna analiza ekspozycji produktów na półkach sklepowych przy użyciu AI</p>', unsafe_allow_html=True)
    
    # Initialize session state
    if 'analysis_results' not in st.session_state:
        st.session_state.analysis_results = None
    if 'recommendations' not in st.session_state:
        st.session_state.recommendations = None
    if 'analysis_history' not in st.session_state:
        st.session_state.analysis_history = []
    if 'openai_api_key' not in st.session_state:
        st.session_state.openai_api_key = ''

    # API Key input
    st.markdown("### 🔑 OpenAI API Configuration")
    api_key_input = st.text_input(
        "Enter your OpenAI API Key",
        type="password",
        value=st.session_state.openai_api_key,
        placeholder="sk-...",
        help="Your API key is stored only for this session and never saved permanently"
    )
    
    if api_key_input != st.session_state.openai_api_key:
        st.session_state.openai_api_key = api_key_input
    
    if not st.session_state.openai_api_key:
        st.warning("⚠️ Please enter your OpenAI API key to use the analyzer. You can get one at: https://platform.openai.com/api-keys")
        st.info("💡 **Tip:** Your API key is only stored temporarily in your browser session and is never saved permanently.")
        return
    
    st.success("✅ API key configured successfully!")
    st.markdown("---")

    # Main interface
    col1, col2 = st.columns([1, 1])
    
    with col1:
        st.markdown("### 📸 Upload zdjęcia półki")
        uploaded_file = st.file_uploader(
            "Wybierz zdjęcie półki sklepowej",
            type=['jpg', 'jpeg', 'png', 'webp'],
            help="Obsługiwane formaty: JPG, PNG, WebP (max 10MB)"
        )
        
        if uploaded_file is not None:
            try:
                image = Image.open(uploaded_file)
                st.image(image, caption="Uploaded Image", use_column_width=True)
                st.session_state.uploaded_image = image
            except Exception as e:
                st.error(f"Błąd przy wczytywaniu obrazu: {str(e)}")
    
    with col2:
        st.markdown("### 🔍 Nazwa produktu")
        product_name = st.text_input(
            "Wpisz nazwę produktu do wyszukania",
            placeholder="np. Coca-Cola 0.5L, Milka czekolada...",
            help="Wpisz konkretną nazwę produktu, który chcesz znaleźć na półce"
        )
        
        st.markdown("### ⚙️ Opcje analizy")
        analysis_depth = st.selectbox(
            "Poziom szczegółowości",
            ["Podstawowy", "Szczegółowy", "Ekspercki"],
            help="Wybierz poziom analizy - im wyższy, tym więcej szczegółów"
        )

    # Analysis button
    if st.button("🚀 Analizuj zdjęcie", type="primary", use_container_width=True):
        if not st.session_state.openai_api_key:
            st.error("⚠️ Proszę najpierw wprowadzić klucz API!")
        elif uploaded_file is None:
            st.error("⚠️ Proszę najpierw wgrać zdjęcie!")
        elif not product_name.strip():
            st.error("⚠️ Proszę wpisać nazwę produktu!")
        else:
            with st.spinner("🤖 Analizuję zdjęcie... To może potrwać do 30 sekund"):
                try:
                    # Convert image to base64 for API
                    buffered = BytesIO()
                    # Convert RGBA to RGB if needed for JPEG
                    if image.mode == 'RGBA':
                        # Create white background
                        rgb_image = Image.new('RGB', image.size, (255, 255, 255))
                        rgb_image.paste(image, mask=image.split()[-1])  # Use alpha channel as mask
                        image = rgb_image
                    image.save(buffered, format="JPEG")
                    image_base64 = base64.b64encode(buffered.getvalue()).decode()
                    
                    # Analyze image
                    analysis_results = analyze_shelf_image(
                        image_base64, 
                        product_name, 
                        analysis_depth
                    )
                    
                    if analysis_results:
                        st.session_state.analysis_results = analysis_results
                        st.session_state.recommendations = generate_recommendations(analysis_results)
                        
                        # Add to history
                        st.session_state.analysis_history.append({
                            'product_name': product_name,
                            'analysis_date': st.session_state.get('current_time', 'Unknown'),
                            'results': analysis_results
                        })
                        
                        st.success("✅ Analiza zakończona pomyślnie!")
                        st.rerun()
                    else:
                        st.error("❌ Wystąpił błąd podczas analizy. Spróbuj ponownie.")
                        
                except Exception as e:
                    st.error(f"❌ Błąd podczas analizy: {str(e)}")

    # Display results
    if st.session_state.analysis_results:
        st.markdown("---")
        st.markdown("## 📊 Wyniki analizy")
        
        # Display analysis results
        display_results(st.session_state.analysis_results, product_name)
        
        # Display recommendations
        if st.session_state.recommendations:
            st.markdown("## 💡 Rekomendacje")
            display_recommendations(st.session_state.recommendations)
            
            # Export options
            col1, col2, col3 = st.columns(3)
            with col1:
                if st.button("📄 Eksportuj do PDF"):
                    st.info("🚧 Funkcja w przygotowaniu")
            with col2:
                if st.button("📧 Wyślij email"):
                    st.info("🚧 Funkcja w przygotowaniu")
            with col3:
                if st.button("🔄 Nowa analiza"):
                    st.session_state.analysis_results = None
                    st.session_state.recommendations = None
                    st.rerun()

    # Sidebar with history and info
    with st.sidebar:
        st.markdown("## 📈 Historia analiz")
        if st.session_state.analysis_history:
            for i, analysis in enumerate(reversed(st.session_state.analysis_history[-5:])):
                with st.expander(f"{analysis['product_name']} ({analysis['analysis_date']})"):
                    score = analysis['results'].get('overall_score', 'N/A')
                    st.write(f"Ocena: {score}/10")
                    if analysis['results'].get('product_found'):
                        st.write("✅ Produkt znaleziony")
                    else:
                        st.write("❌ Produkt nie znaleziony")
        else:
            st.write("Brak historii analiz")
        
        st.markdown("---")
        st.markdown("## ℹ️ Informacje")
        st.markdown("""
        **Jak używać:**
        1. Wgraj zdjęcie półki
        2. Wpisz nazwę produktu
        3. Kliknij "Analizuj"
        4. Otrzymaj rekomendacje
        
        **Wskazówki:**
        - Rób zdjęcia z dobrem oświetleniu
        - Upewnij się, że produkty są widoczne
        - Używaj konkretnych nazw produktów
        """)
        
        st.markdown("---")
        st.markdown("**Powered by OpenAI GPT-4 Vision**")

if __name__ == "__main__":
    main()