Nice — I’ll switch the theme extraction to a data-driven topic model that works with Hebrew text and integrates into your Streamlit app.
What this does:
Preprocesses Hebrew (removes nikud, punctuation, stopwords)
Lets you choose between NMF (TF-IDF) or LDA (Count) topic modeling
Shows top words for each topic, topic assignment for messages, and interactive charts:
topic counts
topics over hours of the day
topics by sender
sample messages per topic
Drop this into app.py (replaces the earlier theme section). You only need to install scikit-learn in addition to the packages you already have.
Install
bashCopy codepip install streamlit pandas requests matplotlib scikit-learn
Streamlit + data-driven Hebrew topics (full code)
pythonCopy code# app.py
import streamlit as st
import pandas as pd
import requests
import re
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation
import numpy as np
st.set_page_config(page_title="Hebrew Topic Explorer", layout="wide")
URL = "https://base44.XXX"
--------------------
Small Hebrew stopword list (expand as needed)
--------------------
HEBREW_STOPWORDS = {
"של","על","עם","את","ה","ל","לה","מה","זה","זו","אלה","אני","אתה","את","הוא","היא",
"אנחנו","הם","הן","יש","אין","כן","לא","או","וגם","אם","כי","כאשר","עוד","כל","כלי",
"יותר","פחות","גם","בעקבות","יותר","שם","אצל","באמת","כמו","עד","בין","כן","נגד","תהיה",
"תהיהו","מעל","מתחת","ידי","מאוד","כך","שזה","שת","שה","שהוא","שלה","שלנו"
}
--------------------
Helpers: preprocess Hebrew text
--------------------
RE_NIKUD = re.compile(r'[\u0591-\u05C7]') # Hebrew diacritics (remove)
RE_NON_HEBREW = re.compile(r'[^א-ת0-9\s]') # keep Hebrew letters, digits and spaces
def preprocess_hebrew(text: str) -> str:
if pd.isna(text):
return ""
s = str(text)
s = RE_NIKUD.sub("", s) # remove nikud
s = s.lower()
s = RE_NON_HEBREW.sub(" ", s) # remove punctuation/latin/other chars
tokens = [t for t in s.split() if len(t)>1 and t not in HEBREW_STOPWORDS]
return " ".join(tokens)
--------------------
Load data
--------------------
@st.cache_data(show_spinner=False)
def load_data(url=URL):
resp = requests.get(url, timeout=30)
resp.raise_for_status()
data = resp.json()
df = pd.DataFrame(data)
# safety: ensure created_date exists and parse
if "created_date" in df.columns:
df["created_date"] = pd.to_datetime(df["created_date"], errors="coerce")
df["hour"] = df["created_date"].dt.hour
df["date"] = df["created_date"].dt.date
else:
df["hour"] = pd.NA
# cleaned text column
df["text_clean"] = df["content"].apply(preprocess_hebrew)
return df
df = load_data()
st.title("🔎 Hebrew Data-driven Theme Extraction")
st.markdown("Topic modeling (NMF or LDA) on the content column. Preprocessing removes nikud, punctuation, and a small stoplist; expand the stoplist or add lemmatization for better results.")
quick data preview
with st.expander("Data preview (first rows)"):
st.dataframe(df.head())
Sidebar controls
st.sidebar.header("Topic model settings")
model_type = st.sidebar.selectbox("Model", ["NMF (TF-IDF)", "LDA (Count)"])
n_topics = st.sidebar.slider("Number of topics", min_value=2, max_value=12, value=4)
max_features = st.sidebar.slider("Max features (vocab size)", 500, 5000, 2000, step=250)
ngram_min, ngram_max = st.sidebar.select_slider("N-gram range (min, max)", options=[1,2], value=(1,2))
n_top_words = st.sidebar.slider("Top words per topic", 3, 15, 7)
If there are no messages after cleaning, warn
if df["text_clean"].str.strip().replace("", pd.NA).isna().all():
st.warning("No usable Hebrew text found after preprocessing. Inspect content and stopwords.")
st.stop()
--------------------
Vectorize + Fit model
--------------------
@st.cache_data(show_spinner=False)
def fit_model(texts, model_type, n_topics, max_features, ngram_range):
# texts: iterable of preprocessed strings
if model_type.startswith("NMF"):
vect = TfidfVectorizer(max_features=max_features, ngram_range=ngram_range)
X = vect.fit_transform(texts)
model = NMF(n_components=n_topics, random_state=0, init="nndsvda", max_iter=400)
W = model.fit_transform(X)
components = model.components_
feature_names = vect.get_feature_names_out()
doc_topic_dist = W / (W.sum(axis=1, keepdims=True) + 1e-9)
return {"vectorizer": vect, "model": model, "components": components, "feature_names": feature_names, "doc_topic_dist": doc_topic_dist}
else:
vect = CountVectorizer(max_features=max_features, ngram_range=ngram_range)
X = vect.fit_transform(texts)
model = LatentDirichletAllocation(n_components=n_topics, random_state=0, max_iter=20)
W = model.fit_transform(X) # document-topic distribution
components = model.components_
feature_names = vect.get_feature_names_out()
doc_topic_dist = W / (W.sum(axis=1, keepdims=True) + 1e-9)
return {"vectorizer": vect, "model": model, "components": components, "feature_names": feature_names, "doc_topic_dist": doc_topic_dist}
with st.spinner("Fitting topic model..."):
info = fit_model(df["text_clean"].fillna(""), model_type, n_topics, max_features, (ngram_min, ngram_max))
components = info["components"]
feature_names = info["feature_names"]
doc_topic_dist = info["doc_topic_dist"]
show top words
def top_words_for_topics(components, feature_names, n_top):
topics = []
for i, topic_vec in enumerate(components):
best_idx = topic_vec.argsort()[:-n_top-1:-1]
words = [feature_names[j] for j in best_idx]
topics.append((i, words))
return topics
topics_top = top_words_for_topics(components, feature_names, n_top_words)
st.header("Top words per topic")
cols = st.columns(1)
for t_idx, words in topics_top:
cols[0].markdown(f"Topic {t_idx} — " + ", ".join(words))
--------------------
Assign topic to each document
--------------------
topic_assignments = np.argmax(doc_topic_dist, axis=1)
df["topic"] = topic_assignments
also add topic probabilities
for k in range(doc_topic_dist.shape[1]):
df[f"topic_{k}_prob"] = doc_topic_dist[:, k]
Topic counts
st.subheader("Topic counts")
topic_counts = df["topic"].value_counts().sort_index()
st.bar_chart(topic_counts)
Topics across hours
if "hour" in df.columns:
st.subheader("Topics by hour of day")
topic_by_hour = df.groupby(["hour", "topic"]).size().unstack(fill_value=0)
st.dataframe(topic_by_hour)
st.bar_chart(topic_by_hour) # stacked per hour
Topics by sender
if "created_by" in df.columns:
st.subheader("Topic distribution by sender (top senders)")
top_senders = df["created_by"].value_counts().head(10).index
tb = df[df["created_by"].isin(top_senders)].groupby(["created_by", "topic"]).size().unstack(fill_value=0)
st.dataframe(tb)
st.bar_chart(tb)
Show sample messages per topic
st.subheader("Sample messages per topic")
samples_per_topic = st.slider("Samples per topic", 1, 10, 5)
for t_idx, words in topics_top:
st.markdown(f"Topic {t_idx} — {', '.join(words)}")
examples = df[df["topic"]==t_idx].sort_values(by=f"topic_{t_idx}_prob", ascending=False).head(samples_per_topic)
if examples.empty:
st.write("No examples for this topic")
else:
# show content, created_by, hour
display_cols = []
if "created_by" in examples.columns:
display_cols.append("created_by")
if "hour" in examples.columns:
display_cols.append("hour")
display_cols += ["content"]
st.table(examples[display_cols].reset_index(drop=True))
Option to export topics
if st.button("Download dataframe with topic labels as CSV"):
csv = df.to_csv(index=False)
st.download_button("Click to download CSV", csv, file_name="messages_with_topics.csv", mime="text/csv")
Guidance & next steps
st.markdown("""
Notes & next steps
- This is unsupervised — interpret the topics by their top words and example messages.
- For better Hebrew results: add more stopwords, and/or add a Hebrew lemmatizer (e.g., spaCy with a Hebrew model or specialized Hebrew NLP libs).
- If you want automatic selection of
n_topics, we can add metrics (coherence / perplexity / reconstruction error) or try clustering on the TF-IDF space.
""")
Notes & suggestions
Preprocessing here is intentionally conservative (simple tokenization and a short stoplist). Adding a Hebrew lemmatizer or stemmer (or expanding the stoplist) will greatly improve topic quality.
NMF (TF-IDF) often gives more human-interpretable topics than LDA for short messages; try both.
If output contains many fragments or stop-words, expand HEBREW_STOPWORDS with frequent function words you see in your data.
If you want, I can:
add automatic topic number selection (using coherence proxies),
integrate interactive filters (session/date/sender) before modelling,
or show how to use a Hebrew lemmatizer (I’ll propose libraries and exact commands).
Which of those would you like next?