File size: 15,792 Bytes
d0e3307 7f7111d d0e3307 b274159 d0e3307 a728d3c d0e3307 d7d4472 5700222 d7d4472 f3f197e d7d4472 5700222 d7d4472 d0e3307 53d317f 7f7111d d0e3307 093632f d0e3307 4c91236 093632f d0e3307 7f7111d ce32f1f d0e3307 7f7111d d0e3307 7f7111d 46c1a7b 125f8fe e978a47 093632f b942b6b 093632f 53d317f d0e3307 53d317f aebb122 53d317f d7d4472 d0e3307 125f8fe d0e3307 9adb120 d86d3e2 d0e3307 b942b6b 4c91236 d0e3307 5700222 d0e3307 5700222 d0e3307 7f7111d d0e3307 5700222 5f8d745 5700222 9adb120 5700222 4c91236 9adb120 4c91236 5700222 7f7111d 5700222 53d317f 093632f 5700222 093632f 5700222 4c91236 53d317f b243899 5700222 d0e3307 ce32f1f 5700222 d0e3307 514a1ba 5700222 d0e3307 514a1ba d0e3307 514a1ba d0e3307 514a1ba d0e3307 514a1ba d0e3307 514a1ba d0e3307 514a1ba d0e3307 514a1ba d0e3307 514a1ba d0e3307 | 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 386 387 388 389 390 391 392 393 | import json, os
from io import StringIO
import pandas as pd
import streamlit as st
from snowflake.snowpark import Session
from bs4 import BeautifulSoup
from Messaging_system.Permes import Permes
from dotenv import load_dotenv
from Messaging_system.SnowFlakeConnection import SnowFlakeConn
load_dotenv()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Helpers
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@st.cache_data
def load_data(buf) -> pd.DataFrame:
return pd.read_csv(buf)
def load_config_(file_path: str) -> dict:
with open(file_path) as f:
return json.load(f)
def get_credential(key):
return os.getenv(key) or st.secrets.get(key)
# Authorized emails
AUTHORIZED_EMAILS = {
"danial@musora.com",
"danial.ebrat@gmail.com",
"simon@musora.com",
"una@musora.com",
"mark@musora.com",
"gabriel@musora.com",
"nikki@musora.com"
}
# --- one env var that holds the shared password / token ---------------------
VALID_TOKEN = get_credential("APP_TOKEN")
# --- small utility -----------------------------------------------------------
def verify_login(email: str, token: str) -> bool:
"""True β’ both the address and the token are valid."""
return (email.lower().strip() in AUTHORIZED_EMAILS) and (token == VALID_TOKEN)
# --- UI: show a form until the user is authenticated ------------------------
if not st.session_state.get("authenticated", False):
st.title("π Sign-in")
st.markdown(
"Access is limited to authorised users. "
"Enter your **e-mail** and the shared **access token**."
)
with st.form("login"):
email = st.text_input("e-mail")
token = st.text_input("access token", type="password")
submitted = st.form_submit_button("Log in")
if submitted:
if verify_login(email, token):
st.session_state.authenticated = True
st.session_state.user_email = email
st.success("Login successful β redirectingβ¦")
st.rerun() # reloads the app, now βinsideβ
else:
st.error("β Invalid e-mail or token")
# IMPORTANT: stop executing the rest of the app while not logged-in
st.stop()
def init_state() -> None:
defaults = dict(
involve_recsys_result=False, personalization=False,
involve_last_interaction=False, session=None,
valid_instructions="",
invalid_instructions="",
messaging_type="push",
generated=False, model=None,
include_recommendation=False,
data=None, brand=None, recsys_contents=[], csv_output=None,
users_message=None, messaging_mode=None, target_column=None,
ugc_column=None, identifier_column=None, input_validator=None,
selected_input_features=None, selected_features=None,
additional_instructions=None, segment_info="", message_style="",
sample_example="", CTA="", all_features=None, number_of_messages=1,
instructionset={}, subsequent_examples={}, segment_name="", number_of_samples=10,
selected_source_features=[], platform=None, generate_clicked=False, config=None,
)
for k, v in defaults.items():
st.session_state.setdefault(k, v)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE CONFIG + THEME
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.set_page_config(
page_title="Personalized Message Generator",
page_icon="π¬",
layout="wide",
initial_sidebar_state="expanded"
)
st.markdown(
"""
<style>
html, body, [class*="css"] {
background-color:#0d0d0d;
color:#ffd700;
}
.stButton>button, .stDownloadButton>button {
border-radius:8px;
background:#ffd700;
color:#0d0d0d;
font-weight:600;
}
.stTabs [data-baseweb="tab"] {
font-weight:600;
}
.stTabs [aria-selected="true"] {
color:#ffd700;
}
h1, h2, h3 {color:#ffd700;}
.small {font-size:0.85rem; opacity:0.7;}
</style>
""",
unsafe_allow_html=True
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SIDEBAR β the βcontrol panelβ
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
init_state()
with st.sidebar:
# β Brand
st.selectbox(
"Select a Brand to Start! *",
["drumeo", "pianote", "guitareo", "singeo"],
key="brand",
)
if st.session_state.brand is not None and st.session_state.session is None:
# β build Snowflake session
conn = dict(
user=get_credential("snowflake_user"),
password=get_credential("snowflake_password"),
account=get_credential("snowflake_account"),
role=get_credential("snowflake_role"),
database=get_credential("snowflake_database"),
warehouse=get_credential("snowflake_warehouse"),
schema=get_credential("snowflake_schema")
)
st.session_state.session = Session.builder.configs(conn).create()
snowflake = SnowFlakeConn(session=st.session_state.session, brand=st.session_state.brand)
st.session_state.data = snowflake.get_inactive_users_by_brand(brand=st.session_state.brand)
st.success("File loaded!")
st.markdown("---")
if st.session_state.data is not None:
id_col = "email"
st.session_state.identifier_column = id_col
st.session_state.config = load_config_("Config_files/message_system_config.json")
# β Brand
st.selectbox(
"LLM model *",
st.session_state.config["LLM_models"],
key="model"
)
# β Personalization
st.text_area("Segment info *", key="segment_info")
st.checkbox("Modify examples to make the message personalized", key="personalization")
# β RecSys
st.checkbox("Include recommendation", key="include_recommendation")
if st.session_state.include_recommendation:
st.multiselect(
"Recommendation types",
["song", "workout", "quick_tips", "course"],
key="recsys_contents"
)
st.text_area("Examples", key="sample_example",
placeholder="Provide examples: The LLM will pick from the options and personalize it for the user.")
st.number_input("Number of samples (default = 10)", 1, 50,
key="number_of_samples")
# β Sequential messages
st.number_input("Sequential messages / user", 1, 12, 1,
key="number_of_messages")
st.text_input("Segment name", key="segment_name",
placeholder="no_recent_activity")
if st.session_state.number_of_messages > 1:
st.caption("Additional per-message instructions")
for i in range(2, st.session_state.number_of_messages + 1):
# st.text_area(f"Message {i} instruction",
# key=f"instr_{i}")
st.text_area(f"Examples for message #{i}",
key=f"ex_{i}",
placeholder="e.g. \"Hey {name}! We miss you β open the app to β¦\"")
st.markdown("---")
if st.button("π Generate messages", key="generate"):
st.session_state.generate_clicked = True # ask for a new run
st.session_state.generated = False # forget old results
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# MAIN AREA β three tabs
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
tab0, tab2 = st.tabs(
["π Data preview", "π¨ Results"])
# ------------------------------------------------------------------ TAB 0 ---#
with tab0:
st.header("π Data preview")
if st.session_state.data is not None:
st.dataframe(st.session_state.data.head(100))
else:
st.info("Select a brand to preview the data here.")
# ------------------------------------------------------------------ TAB 2 ---#
with tab2:
st.header("π¨ Generated messages")
# Run generation only once per click
if st.session_state.generate_clicked and not st.session_state.generated:
if st.session_state.get("generate_clicked", False):
# β prepare parameters
st.session_state.messaging_mode = (
"recsys_result" if st.session_state.include_recommendation
else "message"
)
st.session_state.involve_recsys_result = st.session_state.include_recommendation
st.session_state.instructionset = {
i: st.session_state.get(f"instr_{i}")
for i in range(2, st.session_state.number_of_messages + 1)
if st.session_state.get(f"instr_{i}", "").strip()
}
st.session_state.subsequent_examples = {
i: st.session_state.get(f"ex_{i}")
for i in range(2, st.session_state.number_of_messages + 1)
if st.session_state.get(f"ex_{i}", "").strip()
}
# β progress callback
prog = st.progress(0)
status = st.empty()
def cb(done, total):
pct = int(done / total * 100)
prog.progress(pct)
status.write(f"{pct}%")
permes = Permes()
df_msg = permes.create_personalize_messages(
session=st.session_state.session,
users=st.session_state.data,
brand=st.session_state.brand,
segment_info=st.session_state.segment_info,
config_file=st.session_state.config,
openai_api_key=get_credential("OPENAI_API"),
model=st.session_state.model,
number_of_samples=st.session_state.number_of_samples,
sample_example=st.session_state.sample_example,
platform=st.session_state.messaging_type,
involve_recsys_result=st.session_state.involve_recsys_result,
messaging_mode=st.session_state.messaging_mode,
identifier_column=st.session_state.identifier_column,
recsys_contents=st.session_state.recsys_contents,
progress_callback=cb,
number_of_messages=st.session_state.number_of_messages,
instructionset=st.session_state.instructionset,
subsequent_examples = st.session_state.subsequent_examples,
segment_name=st.session_state.segment_name,
personalization=st.session_state.personalization
)
if df_msg is None:
st.write("##### π€ There were no eligible user to generate messages. Consider setting higher number of users.")
# β cache output
st.session_state.users_message = df_msg
st.session_state.csv_output = df_msg.to_csv(
index=False, encoding="utf-8-sig")
st.session_state.generated = True
st.session_state.generate_clicked = False
prog.empty(); status.empty()
st.balloons()
# =============================================================
if st.session_state.get("generated", False):
df = st.session_state.users_message
id_col = st.session_state.identifier_column or ""
id_col_lower = id_col.lower()
# expandable per-user cards
for i, (_, row) in enumerate(df.iterrows(), start=1):
user_id = row.get(id_col_lower, "(no ID)")
with st.expander(f"{i}. User ID: {user_id}", expanded=(i == 1)):
# --- Features
st.write("##### π€ Features")
feats = st.session_state.selected_source_features or []
cols = st.columns(3)
for idx, feature in enumerate(feats):
val = row.get(feature, "β")
cols[idx % 3].markdown(f"**{feature}**: {val}")
st.markdown("---")
# --- Messages
st.write("##### βοΈ Messages")
raw = row.get("message", "")
# try to parse JSON if it's a str
if isinstance(raw, str):
try:
blob = json.loads(raw)
except json.JSONDecodeError:
st.error(f"Could not parse JSON for user {user_id}")
continue
elif isinstance(raw, dict) or isinstance(raw, list):
blob = raw
else:
blob = {}
# extract sequence
if isinstance(blob, dict):
seq = blob.get("messages_sequence", [])
elif isinstance(blob, list):
seq = blob
else:
seq = []
# make sure it's a list
if not isinstance(seq, list):
seq = [seq]
# render each message
for j, msg in enumerate(seq, start=1):
if not isinstance(msg, dict):
# if it's just a string or number, render it plainly
st.markdown(f"**{j}. (no header)**")
st.markdown(str(msg))
st.markdown("---")
continue
header = msg.get("header", "(no header)")
st.markdown(f"**{j}. {header}**")
# optional title
title = msg.get("title")
if title:
st.markdown(f"**Title:** {title}")
# thumbnail (per-message or fallback per-user)
thumb = msg.get("thumbnail_url") or row.get("thumbnail_url")
if thumb:
st.image(thumb, width=150)
# the main message body
body = msg.get("message", "")
st.markdown(body)
# optional "read more" link
url = msg.get("web_url_path")
if url:
st.markdown(f"[Read more]({url})")
st.markdown("---")
|