-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
259 lines (229 loc) · 10.2 KB
/
streamlit_app.py
File metadata and controls
259 lines (229 loc) · 10.2 KB
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
import streamlit as st
import pandas as pd
import numpy as np
import re
from sklearn.preprocessing import LabelEncoder
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from collections import defaultdict
from random import choice
st.set_page_config(page_title="AI Content Strategy App")
st.title("AI Content Strategy App")
def optimal_clusters(values, max_clusters=8):
X = values.reshape(-1, 1)
best_k, best_score = 2, -1
for k in range(2, min(max_clusters, len(values)) + 1):
km = KMeans(n_clusters=k, n_init="auto", random_state=42)
labels = km.fit_predict(X)
if len(set(labels)) == 1:
continue
score = silhouette_score(X, labels)
if score > best_score:
best_k, best_score = k, score
return best_k
uploaded = st.file_uploader("Upload customer CSV", type="csv")
if uploaded is not None:
df = pd.read_csv(uploaded)
df.columns = df.columns.str.lower()
required = {"industry", "product", "amount", "credit_score", "tenure"}
if not required.issubset(df.columns):
st.error(
"CSV must contain columns: industry, product, amount, credit_score, tenure"
)
st.stop()
ind_enc = LabelEncoder()
df["industry_code"] = ind_enc.fit_transform(df["industry"].astype(str))
ind_k = optimal_clusters(df["industry_code"].values)
st.write(f"Detected {ind_k} industry clusters")
ind_kmeans = KMeans(n_clusters=ind_k, n_init="auto", random_state=42)
df["industry_cluster"] = ind_kmeans.fit_predict(df[["industry_code"]])
df["product_cluster"] = -1
prod_cluster_counts = {}
for i in sorted(df["industry_cluster"].unique()):
subset = df[df["industry_cluster"] == i]
prod_enc = LabelEncoder()
codes = prod_enc.fit_transform(subset["product"].astype(str))
n_unique = len(np.unique(codes))
if n_unique <= 1:
prod_k = 1
else:
prod_k = optimal_clusters(codes)
km = KMeans(n_clusters=prod_k, n_init="auto", random_state=42)
df.loc[subset.index, "product_cluster"] = km.fit_predict(codes.reshape(-1, 1))
prod_cluster_counts[i] = prod_k
st.subheader("Industry Cluster Summary")
summary = (
df.groupby("industry_cluster")
.agg(
industry=("industry", lambda s: ", ".join(sorted(s.unique()))),
total_amount=("amount", "sum"),
avg_credit_score=("credit_score", "mean"),
avg_tenure=("tenure", "mean"),
)
.sort_values("total_amount", ascending=False)
)
st.dataframe(summary)
sel_ind = st.number_input(
"How many ranked industry clusters to include?",
min_value=1,
max_value=len(summary),
value=min(3, len(summary)),
)
ind_to_use = summary.head(sel_ind).index.tolist()
selected_prod = defaultdict(int)
for i in ind_to_use:
prod_df = df[df["industry_cluster"] == i]
prod_summary = (
prod_df.groupby("product_cluster")
.agg(
industry=("industry", lambda s: ", ".join(sorted(s.unique()))),
product=("product", lambda s: ", ".join(sorted(s.unique()))),
total_amount=("amount", "sum"),
avg_credit_score=("credit_score", "mean"),
avg_tenure=("tenure", "mean"),
)
.sort_values("total_amount", ascending=False)
)
max_prod = prod_cluster_counts[i]
n_prod = st.number_input(
f"Industry cluster {i}: how many top product clusters to include?",
min_value=1,
max_value=max_prod,
value=max_prod,
)
selected_prod[i] = n_prod
st.dataframe(prod_summary)
# --- Updated keyword input and multiselect ---
raw_msg_keywords = st.text_input(
"Enter keywords or context for marketing messages (comma-separated)",
key="raw_msg_kw",
placeholder="Best bank for SMEs, digital banking, business growth",
)
raw_prod_keywords = st.text_input(
"Enter keywords or context for product propositions (comma-separated)",
key="raw_prod_kw",
placeholder="Low-fee business banking, fast approval, cash flow support",
)
msg_kw_options = [k.strip() for k in re.split(r"[,\n]+", raw_msg_keywords) if k.strip()]
prod_kw_options = [k.strip() for k in re.split(r"[,\n]+", raw_prod_keywords) if k.strip()]
msg_kw_list = st.multiselect(
"Select keywords for marketing messages", options=msg_kw_options, default=msg_kw_options
)
prod_kw_list = st.multiselect(
"Select keywords for product propositions", options=prod_kw_options, default=prod_kw_options
)
# --- End update ---
num_message_variants = st.number_input(
"Number of message variants per industry cluster",
min_value=1,
max_value=10,
value=3,
)
num_product_props = st.number_input(
"Number of product propositions per product cluster",
min_value=1,
max_value=10,
value=3,
)
temperature = st.slider(
"Adjust Creativity Level", min_value=0.0, max_value=1.0, value=0.5, step=0.05
)
use_llm = st.checkbox(
"Generate suggestions with Gemma-2B-IT (requires internet and may be slow)",
value=False,
)
if st.button("Configure Experiment"):
selected_variants = []
for i in ind_to_use:
prod_df = df[df["industry_cluster"] == i]
prod_summary = (
prod_df.groupby("product_cluster")
.agg(
industry=("industry", lambda s: ", ".join(sorted(s.unique()))),
product=("product", lambda s: ", ".join(sorted(s.unique()))),
total_amount=("amount", "sum"),
avg_credit_score=("credit_score", "mean"),
avg_tenure=("tenure", "mean"),
)
.sort_values("total_amount", ascending=False)
)
prods = prod_summary.head(selected_prod[i]).index.tolist()
for p in prods:
selected_variants.append((i, p))
def generate_text(prompt: str) -> str:
"""Generate text using the Gemma model via the Hugging Face Hub.
Requires the ``HF_TOKEN`` environment variable to be set with a
token that has access to ``google/gemma-2b-it``.
"""
import os
from huggingface_hub import InferenceClient
model_id = "google/gemma-2b-it"
token = os.getenv("HF_TOKEN")
client = InferenceClient(model=model_id, token=token)
# Use the conversational endpoint for generation
messages = [{"role": "user", "content": prompt}]
response = client.chat_completion(
messages,
max_tokens=1000,
temperature=temperature,
)
return response.choices[0].message.content
messages = []
if use_llm and (msg_kw_list or prod_kw_list):
ind_summary_text = summary.loc[ind_to_use].to_markdown()
prod_summary_texts = []
for i in ind_to_use:
prod_df = df[df["industry_cluster"] == i]
prod_summary = (
prod_df.groupby("product_cluster")
.agg(
product=("product", lambda s: ", ".join(sorted(s.unique()))),
total_amount=("amount", "sum"),
)
.sort_values("total_amount", ascending=False)
)
prod_summary_texts.append(
f"Industry {i}:\n" + prod_summary.head(selected_prod[i]).to_markdown()
)
prod_text = "\n\n".join(prod_summary_texts)
prompt = (
f"You are a seasoned content strategist and content creator for a financial services company targeting SME audiences. "
f"Your task is to develop compelling, high-impact content that aligns with the specified industry and product clusters. "
f"Use the provided keyword sets to craft messaging and propositions that are relevant, engaging, and conversion-oriented.\n\n"
f"For each industry cluster listed below, generate {num_message_variants} short marketing message variants. "
f"Each message should:\n"
f"- Incorporate at least one of the following marketing keywords: {', '.join(msg_kw_list)}\n"
f"- Reflect a tone of voice suitable for SME decision-makers (clear, benefit-driven, and concise)\n"
f"- Be no longer than 100 words\n\n"
f"For each product cluster, propose {num_product_props} concise product proposition statements. "
f"Each proposition should:\n"
f"- Use one or more of these product-related keywords: {', '.join(prod_kw_list)}\n"
f"- Highlight key business outcomes, not just features (e.g., 'improve cash flow', 'simplify operations')\n"
f"- Be phrased in a benefit-first, SME-friendly tone\n"
f"- Stay under 100 words\n\n"
f"=== INPUTS ===\n\n"
f" Industry Clusters:\n{ind_summary_text}\n\n"
f" Product Clusters:\n{prod_text}\n\n"
)
try:
generated = generate_text(prompt)
messages = [line.strip() for line in generated.split("\n") if line.strip()]
except Exception as e:
messages = [f"LLM generation failed: {e}"]
assignments = []
variant_texts = []
for _, row in df.iterrows():
variant = choice(selected_variants)
assignments.append(f"I{variant[0]}-P{variant[1]}")
variant_texts.append(f"Industry {variant[0]} / Product {variant[1]}")
df["variant"] = assignments
df["variant_text"] = variant_texts
st.subheader("Variant assignments")
st.dataframe(df[["industry", "product", "variant", "variant_text"]])
if messages:
st.subheader("AI Suggestions")
suggestions_md = "\n\n".join(messages)
st.markdown(
suggestions_md,
unsafe_allow_html=True,
)