File size: 12,921 Bytes
822ac98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5188b7
 
 
822ac98
 
 
 
 
 
 
 
 
c5188b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822ac98
 
 
 
c5188b7
822ac98
 
c5188b7
 
822ac98
c5188b7
 
 
 
822ac98
c5188b7
 
 
 
 
 
 
 
 
 
 
 
 
 
822ac98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5188b7
 
 
822ac98
 
 
c5188b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822ac98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""
AI Messaging System - Visualization Tool
Main entry point with authentication and brand selection.
"""

import streamlit as st
import sys
from pathlib import Path
from dotenv import load_dotenv

# Load environment variables from .env file FIRST
env_path = Path(__file__).parent / '.env'
if env_path.exists():
    load_dotenv(env_path)
else:
    # Try parent directory .env as fallback
    parent_env_path = Path(__file__).parent.parent / '.env'
    if parent_env_path.exists():
        load_dotenv(parent_env_path)

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from utils.auth import verify_login, check_authentication, get_current_user, logout
from utils.theme import apply_theme, get_brand_emoji, get_brand_theme
from utils.data_loader import DataLoader
from utils.config_manager import ConfigManager
from snowflake.snowpark import Session
import os

# Page configuration
st.set_page_config(
    page_title="AI Messaging System - Visualization",
    page_icon="🎡",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Helper function to create Snowflake session
def create_snowflake_session() -> Session:
    """Create a Snowflake session using environment variables."""
    conn_params = {
        "user": os.getenv("SNOWFLAKE_USER"),
        "password": os.getenv("SNOWFLAKE_PASSWORD"),
        "account": os.getenv("SNOWFLAKE_ACCOUNT"),
        "role": os.getenv("SNOWFLAKE_ROLE"),
        "database": os.getenv("SNOWFLAKE_DATABASE"),
        "warehouse": os.getenv("SNOWFLAKE_WAREHOUSE"),
        "schema": os.getenv("SNOWFLAKE_SCHEMA"),
    }
    return Session.builder.configs(conn_params).create()


# Initialize session state
def init_session_state():
    """Initialize session state variables."""
    defaults = {
        # Authentication
        "authenticated": False,
        "user_email": "",

        # Brand and configs
        "selected_brand": None,
        "cached_configs": {},  # Cache configs per brand: {brand: {config_name: config_data}}
        "configs_loaded": False,

        # Current experiment data (in-memory)
        "current_experiment_id": None,
        "ui_log_data": None,  # Accumulated dataframe for multi-stage messages
        "current_experiment_metadata": [],  # List of metadata dicts per stage
        "current_feedbacks": [],  # List of feedback dicts

        # AB Testing data
        "ab_testing_mode": False,
        "ui_log_data_a": None,
        "ui_log_data_b": None,
        "experiment_a_id": None,
        "experiment_b_id": None,
        "experiment_a_metadata": [],
        "experiment_b_metadata": [],
        "feedbacks_a": [],
        "feedbacks_b": [],
    }
    for key, value in defaults.items():
        if key not in st.session_state:
            st.session_state[key] = value


init_session_state()

# Authentication check
if not check_authentication():
    # Show login page
    st.title("πŸ” AI Messaging System - Login")

    st.markdown("""
    Welcome to the **AI Messaging System Visualization Tool**!

    This tool enables you to:
    - πŸ—οΈ Build and configure message campaigns
    - πŸ‘€ Visualize generated messages across all stages
    - πŸ“Š Analyze performance and provide feedback
    - πŸ§ͺ Run A/B tests to compare different approaches

    ---

    **Access is restricted to authorized team members only.**
    Please enter your credentials below.
    """)

    with st.form("login_form"):
        email = st.text_input("πŸ“§ Email Address", placeholder="your.name@musora.com")
        token = st.text_input("πŸ”‘ Access Token", type="password", placeholder="Enter your access token")
        submit = st.form_submit_button("πŸš€ Login", use_container_width=True)

    if submit:
        if verify_login(email, token):
            st.session_state.authenticated = True
            st.session_state.user_email = email
            st.success("βœ… Login successful! Redirecting...")
            st.rerun()
        else:
            st.error("❌ Invalid email or access token. Please try again.")

    st.stop()

# User is authenticated - show main app
# Apply base theme initially
apply_theme("base")

# Sidebar - Brand Selection
with st.sidebar:
    st.title("🎡 AI Messaging System")

    st.markdown(f"**Logged in as:** {get_current_user()}")

    if st.button("πŸšͺ Logout", use_container_width=True):
        logout()
        st.rerun()

    st.markdown("---")

    # Brand Selection
    st.subheader("🎨 Select Brand")

    brands = ["drumeo", "pianote", "guitareo", "singeo"]
    brand_labels = {
        "drumeo": "πŸ₯ Drumeo",
        "pianote": "🎹 Pianote",
        "guitareo": "🎸 Guitareo",
        "singeo": "🎀 Singeo"
    }

    # Get current brand from session state if exists
    current_brand = st.session_state.get("selected_brand", brands[0])

    selected_brand = st.selectbox(
        "Brand",
        brands,
        index=brands.index(current_brand) if current_brand in brands else 0,
        format_func=lambda x: brand_labels[x],
        key="brand_selector",
        label_visibility="collapsed"
    )

    # Check if brand changed
    brand_changed = (st.session_state.selected_brand != selected_brand)

    # Update session state with selected brand
    st.session_state.selected_brand = selected_brand

    # Load configs from Snowflake if brand changed or not loaded yet
    if brand_changed or not st.session_state.get("configs_loaded", False):
        if selected_brand:
            with st.spinner(f"Loading configurations for {selected_brand}..."):
                try:
                    # Create Snowflake session for config loading
                    session = create_snowflake_session()

                    # Initialize config manager with session
                    config_manager = ConfigManager(session)

                    # Load all configs for this brand
                    configs = config_manager.get_all_configs(selected_brand)

                    # Cache in session state
                    if selected_brand not in st.session_state.cached_configs:
                        st.session_state.cached_configs[selected_brand] = {}
                    st.session_state.cached_configs[selected_brand] = configs
                    st.session_state.configs_loaded = True

                    # Close session after loading
                    session.close()

                    st.success(f"βœ… Loaded {len(configs)} configurations from Snowflake")

                except Exception as e:
                    st.error(f"❌ Error loading configs from Snowflake: {e}")
                    st.info("πŸ’‘ Make sure Snowflake credentials are set in .env file")

    # Apply brand theme
    if selected_brand:
        apply_theme(selected_brand)

    st.markdown("---")

    # Navigation info
    st.subheader("πŸ“– Navigation")
    st.markdown("""
    Use the pages in the sidebar to navigate:
    - **Campaign Builder**: Create campaigns & A/B tests
    - **Message Viewer**: Review messages
    - **Analytics**: View current performance
    - **Historical Analytics**: Track improvements
    """)

# Main Content Area
if not selected_brand:
    st.title("🎡 Welcome to AI Messaging System")

    st.markdown("""
    ### Get Started

    **Please select a brand from the sidebar to begin.**

    Once you've selected a brand, you can:

    1. **Build Campaigns** - Configure and generate personalized messages
    2. **View Messages** - Browse and provide feedback on generated messages
    3. **Run A/B Tests** - Compare different configurations side-by-side
    4. **Analyze Results** - Review performance metrics and insights
    """)

    # Show feature cards
    col1, col2 = st.columns(2)

    with col1:
        st.markdown("""
        #### πŸ—οΈ Campaign Builder
        - Configure multi-stage campaigns
        - Built-in A/B testing mode
        - Parallel experiment processing
        - Automatic experiment archiving
        - Save custom configurations
        """)

        st.markdown("""
        #### πŸ‘€ Message Viewer
        - View all generated messages
        - Side-by-side A/B comparison
        - User-centric or stage-centric views
        - Search and filter messages
        - Provide detailed feedback
        """)

    with col2:
        st.markdown("""
        #### πŸ“Š Analytics Dashboard
        - Real-time performance metrics
        - A/B test winner determination
        - Rejection reason analysis
        - Stage-by-stage performance
        - Export capabilities
        """)

        st.markdown("""
        #### πŸ“š Historical Analytics
        - Track all past experiments
        - Rejection rate trends over time
        - Compare historical A/B tests
        - Export historical data
        """)

else:
    # Brand is selected - show brand-specific homepage
    emoji = get_brand_emoji(selected_brand)
    theme = get_brand_theme(selected_brand)

    st.title(f"{emoji} {selected_brand.title()} - AI Messaging System")

    st.markdown(f"""
    ### Welcome to {selected_brand.title()} Message Generation!

    You're all set to create personalized messages for {selected_brand.title()} users.
    """)

    # Quick stats
    data_loader = DataLoader()

    # Check if we have brand users
    has_users = data_loader.has_brand_users(selected_brand)

    # Check if we have generated messages
    messages_df = data_loader.load_generated_messages()
    has_messages = messages_df is not None and len(messages_df) > 0

    st.markdown("---")

    # Status cards
    col1, col2, col3 = st.columns(3)

    with col1:
        st.markdown("### πŸ‘₯ Available Users")
        if has_users:
            user_count = data_loader.get_brand_user_count(selected_brand)
            st.metric("Users Available", user_count)
            st.success(f"βœ… {user_count} users ready")
        else:
            st.metric("Users Available", 0)
            st.info("ℹ️ No users available")

    with col2:
        st.markdown("### πŸ“¨ Generated Messages")
        if has_messages:
            stats = data_loader.get_message_stats()
            st.metric("Total Messages", stats['total_messages'])
            st.success(f"βœ… {stats['total_stages']} stages")
        else:
            st.metric("Total Messages", 0)
            st.info("ℹ️ No messages generated yet")

    with col3:
        st.markdown("### 🎯 Quick Actions")
        st.markdown("")  # spacing
        if st.button("πŸ—οΈ Build Campaign", use_container_width=True):
            st.switch_page("pages/1_Campaign_Builder.py")
        if has_messages:
            if st.button("πŸ‘€ View Messages", use_container_width=True):
                st.switch_page("pages/2_Message_Viewer.py")

    st.markdown("---")

    # Getting started guide
    st.markdown("### πŸš€ Quick Start Guide")

    st.markdown("""
    #### Step 1: Build a Campaign
    Navigate to **Campaign Builder** to:
    - Toggle A/B testing mode on/off as needed
    - Select number of users to experiment with (1-25)
    - Configure campaign stages (or two experiments side-by-side)
    - Set LLM models and instructions
    - Generate personalized messages with automatic archiving

    #### Step 2: Review Messages
    Go to **Message Viewer** to:
    - Browse all generated messages
    - View A/B tests side-by-side automatically
    - Switch between user-centric and stage-centric views
    - Provide detailed feedback with rejection reasons
    - Track message headers and content

    #### Step 3: Analyze Performance
    Check **Analytics Dashboard** for:
    - Real-time approval and rejection rates
    - A/B test comparisons with winner determination
    - Common rejection reasons with visual charts
    - Stage-by-stage performance insights
    - Export analytics data

    #### Step 4: Track Improvements
    View **Historical Analytics** to:
    - See all past experiments over time
    - Identify rejection rate trends
    - Compare historical A/B tests
    - Export comprehensive historical data
    """)

    st.markdown("---")

    # Tips
    with st.expander("πŸ’‘ Tips & Best Practices"):
        st.markdown("""
        - **User Selection**: Select 1-25 users for quick experimentation
        - **Configuration Templates**: Start with default configurations and customize as needed
        - **A/B Testing**: Enable A/B mode in Campaign Builder to compare two configurations in parallel
        - **Feedback**: Reject poor messages with specific categories including the new 'Similar To Previous' option
        - **Historical Tracking**: Check Historical Analytics regularly to track improvements over time
        - **Stage Design**: Each stage should build upon previous stages with varied messaging approaches
        - **Automatic Archiving**: Previous experiments are automatically archived when you start a new one
        """)

st.markdown("---")
st.markdown("**Built with ❀️ for the Musora team**")