Sonnyjim commited on
Commit
1f1a1c7
1 Parent(s): 731ed23

Changed Phi model to smaller StableLM 2 1.6. Fixed a None type detection error.

Browse files
app.py CHANGED
@@ -87,8 +87,8 @@ embeddings_name = "BAAI/bge-small-en-v1.5" #"jinaai/jina-embeddings-v2-base-en"
87
  #revision_choice = "69d43700292701b06c24f43b96560566a4e5ad1f"
88
 
89
  # Model used for representing topics
90
- hf_model_name = 'TheBloke/phi-2-orange-GGUF' #'NousResearch/Nous-Capybara-7B-V1.9-GGUF' # 'second-state/stablelm-2-zephyr-1.6b-GGUF'
91
- hf_model_file = 'phi-2-orange.Q5_K_M.gguf' #'Capybara-7B-V1.9-Q5_K_M.gguf' # 'stablelm-2-zephyr-1_6b-Q5_K_M.gguf'
92
 
93
  def save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model, progress=gr.Progress()):
94
  topic_dets = topic_model.get_topic_info()
@@ -227,7 +227,15 @@ def extract_topics(data, in_files, min_docs_slider, in_colnames, max_topics_slid
227
  nr_topics = max_topics_slider,
228
  verbose = True)
229
 
230
- topics_text, probs = topic_model.fit_transform(docs, embeddings_out)
 
 
 
 
 
 
 
 
231
 
232
 
233
  # Do this if you have pre-defined topics
@@ -254,13 +262,13 @@ def extract_topics(data, in_files, min_docs_slider, in_colnames, max_topics_slid
254
 
255
  # print(topics_text)
256
 
257
- if topics_text.size == 0:
258
- # Handle the empty array case
259
 
260
- return "No topics found.", data_file_name, None, embeddings_out, data_file_name_no_ext, topic_model, docs, label_list
261
 
262
- else:
263
- print("Topic model created.")
264
 
265
  # Outputs
266
  output_list, output_text = save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model)
@@ -319,8 +327,8 @@ def reduce_outliers(topic_model, docs, embeddings_out, data_file_name_no_ext, lo
319
  topic_dets = topic_model.get_topic_info()
320
 
321
  # Replace original labels with LLM labels
322
- if "Phi" in topic_model.get_topic_info().columns:
323
- llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["Phi"].values()]
324
  topic_model.set_topic_labels(llm_labels)
325
  else:
326
  topic_model.set_topic_labels(list(topic_dets["Name"]))
@@ -355,14 +363,14 @@ def represent_topics(topic_model, docs, embeddings_out, data_file_name_no_ext, l
355
  topic_model.update_topics(docs, topics=topics_text, vectorizer_model=vectoriser_model, representation_model=representation_model)
356
 
357
  # Replace original labels with LLM labels
358
- if "Phi" in topic_model.get_topic_info().columns:
359
- llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["Phi"].values()]
360
  topic_model.set_topic_labels(llm_labels)
361
 
362
- with open('llm_topic_list.txt', 'w') as file:
363
  for item in llm_labels:
364
  file.write(f"{item}\n")
365
- output_list.append('llm_topic_list.txt')
366
  else:
367
  topic_model.set_topic_labels(list(topic_dets["Name"]))
368
 
@@ -386,8 +394,8 @@ def visualise_topics(topic_model, docs, data_file_name_no_ext, low_resource_mode
386
  topic_dets = topic_model.get_topic_info()
387
 
388
  # Replace original labels with LLM labels
389
- if "Phi" in topic_model.get_topic_info().columns:
390
- llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["Phi"].values()]
391
  topic_model.set_topic_labels(llm_labels)
392
  else:
393
  topic_model.set_topic_labels(list(topic_dets["Name"]))
 
87
  #revision_choice = "69d43700292701b06c24f43b96560566a4e5ad1f"
88
 
89
  # Model used for representing topics
90
+ hf_model_name = 'second-state/stablelm-2-zephyr-1.6b-GGUF' #'TheBloke/phi-2-orange-GGUF' #'NousResearch/Nous-Capybara-7B-V1.9-GGUF' # 'second-state/stablelm-2-zephyr-1.6b-GGUF'
91
+ hf_model_file = 'stablelm-2-zephyr-1_6b-Q5_K_M.gguf' # 'phi-2-orange.Q5_K_M.gguf' #'Capybara-7B-V1.9-Q5_K_M.gguf' # 'stablelm-2-zephyr-1_6b-Q5_K_M.gguf'
92
 
93
  def save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model, progress=gr.Progress()):
94
  topic_dets = topic_model.get_topic_info()
 
227
  nr_topics = max_topics_slider,
228
  verbose = True)
229
 
230
+ topics_text, probs = topic_model.fit_transform(docs, embeddings_out)
231
+
232
+ if not topics_text:
233
+ # Handle the empty array case
234
+
235
+ return "No topics found.", data_file_name, None, embeddings_out, data_file_name_no_ext, topic_model, docs, label_list
236
+
237
+ else:
238
+ print("Topic model created.")
239
 
240
 
241
  # Do this if you have pre-defined topics
 
262
 
263
  # print(topics_text)
264
 
265
+ if topics_text.size == 0:
266
+ # Handle the empty array case
267
 
268
+ return "No topics found.", data_file_name, None, embeddings_out, data_file_name_no_ext, topic_model, docs, label_list
269
 
270
+ else:
271
+ print("Topic model created.")
272
 
273
  # Outputs
274
  output_list, output_text = save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model)
 
327
  topic_dets = topic_model.get_topic_info()
328
 
329
  # Replace original labels with LLM labels
330
+ if "LLM" in topic_model.get_topic_info().columns:
331
+ llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["LLM"].values()]
332
  topic_model.set_topic_labels(llm_labels)
333
  else:
334
  topic_model.set_topic_labels(list(topic_dets["Name"]))
 
363
  topic_model.update_topics(docs, topics=topics_text, vectorizer_model=vectoriser_model, representation_model=representation_model)
364
 
365
  # Replace original labels with LLM labels
366
+ if "LLM" in topic_model.get_topic_info().columns:
367
+ llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["LLM"].values()]
368
  topic_model.set_topic_labels(llm_labels)
369
 
370
+ with open('llm_topic_list.csv', 'w') as file:
371
  for item in llm_labels:
372
  file.write(f"{item}\n")
373
+ output_list.append('llm_topic_list.csv')
374
  else:
375
  topic_model.set_topic_labels(list(topic_dets["Name"]))
376
 
 
394
  topic_dets = topic_model.get_topic_info()
395
 
396
  # Replace original labels with LLM labels
397
+ if "LLM" in topic_model.get_topic_info().columns:
398
+ llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["LLM"].values()]
399
  topic_model.set_topic_labels(llm_labels)
400
  else:
401
  topic_model.set_topic_labels(list(topic_dets["Name"]))
funcs/bertopic_hierarchical_documents.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import plotly.graph_objects as go
4
+ import math
5
+
6
+ from umap import UMAP
7
+ from typing import List, Union
8
+
9
+
10
+ def visualize_hierarchical_documents(topic_model,
11
+ docs: List[str],
12
+ hierarchical_topics: pd.DataFrame,
13
+ topics: List[int] = None,
14
+ embeddings: np.ndarray = None,
15
+ reduced_embeddings: np.ndarray = None,
16
+ sample: Union[float, int] = None,
17
+ hide_annotations: bool = False,
18
+ hide_document_hover: bool = True,
19
+ nr_levels: int = 10,
20
+ level_scale: str = 'linear',
21
+ custom_labels: Union[bool, str] = False,
22
+ title: str = "<b>Hierarchical Documents and Topics</b>",
23
+ width: int = 1200,
24
+ height: int = 750) -> go.Figure:
25
+ """ Visualize documents and their topics in 2D at different levels of hierarchy
26
+
27
+ Arguments:
28
+ docs: The documents you used when calling either `fit` or `fit_transform`
29
+ hierarchical_topics: A dataframe that contains a hierarchy of topics
30
+ represented by their parents and their children
31
+ topics: A selection of topics to visualize.
32
+ Not to be confused with the topics that you get from `.fit_transform`.
33
+ For example, if you want to visualize only topics 1 through 5:
34
+ `topics = [1, 2, 3, 4, 5]`.
35
+ embeddings: The embeddings of all documents in `docs`.
36
+ reduced_embeddings: The 2D reduced embeddings of all documents in `docs`.
37
+ sample: The percentage of documents in each topic that you would like to keep.
38
+ Value can be between 0 and 1. Setting this value to, for example,
39
+ 0.1 (10% of documents in each topic) makes it easier to visualize
40
+ millions of documents as a subset is chosen.
41
+ hide_annotations: Hide the names of the traces on top of each cluster.
42
+ hide_document_hover: Hide the content of the documents when hovering over
43
+ specific points. Helps to speed up generation of visualizations.
44
+ nr_levels: The number of levels to be visualized in the hierarchy. First, the distances
45
+ in `hierarchical_topics.Distance` are split in `nr_levels` lists of distances.
46
+ Then, for each list of distances, the merged topics are selected that have a
47
+ distance less or equal to the maximum distance of the selected list of distances.
48
+ NOTE: To get all possible merged steps, make sure that `nr_levels` is equal to
49
+ the length of `hierarchical_topics`.
50
+ level_scale: Whether to apply a linear or logarithmic (log) scale levels of the distance
51
+ vector. Linear scaling will perform an equal number of merges at each level
52
+ while logarithmic scaling will perform more mergers in earlier levels to
53
+ provide more resolution at higher levels (this can be used for when the number
54
+ of topics is large).
55
+ custom_labels: If bool, whether to use custom topic labels that were defined using
56
+ `topic_model.set_topic_labels`.
57
+ If `str`, it uses labels from other aspects, e.g., "Aspect1".
58
+ NOTE: Custom labels are only generated for the original
59
+ un-merged topics.
60
+ title: Title of the plot.
61
+ width: The width of the figure.
62
+ height: The height of the figure.
63
+
64
+ Examples:
65
+
66
+ To visualize the topics simply run:
67
+
68
+ ```python
69
+ topic_model.visualize_hierarchical_documents(docs, hierarchical_topics)
70
+ ```
71
+
72
+ Do note that this re-calculates the embeddings and reduces them to 2D.
73
+ The advised and prefered pipeline for using this function is as follows:
74
+
75
+ ```python
76
+ from sklearn.datasets import fetch_20newsgroups
77
+ from sentence_transformers import SentenceTransformer
78
+ from bertopic import BERTopic
79
+ from umap import UMAP
80
+
81
+ # Prepare embeddings
82
+ docs = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))['data']
83
+ sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
84
+ embeddings = sentence_model.encode(docs, show_progress_bar=False)
85
+
86
+ # Train BERTopic and extract hierarchical topics
87
+ topic_model = BERTopic().fit(docs, embeddings)
88
+ hierarchical_topics = topic_model.hierarchical_topics(docs)
89
+
90
+ # Reduce dimensionality of embeddings, this step is optional
91
+ # reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings)
92
+
93
+ # Run the visualization with the original embeddings
94
+ topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, embeddings=embeddings)
95
+
96
+ # Or, if you have reduced the original embeddings already:
97
+ topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)
98
+ ```
99
+
100
+ Or if you want to save the resulting figure:
101
+
102
+ ```python
103
+ fig = topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)
104
+ fig.write_html("path/to/file.html")
105
+ ```
106
+
107
+ NOTE:
108
+ This visualization was inspired by the scatter plot representation of Doc2Map:
109
+ https://github.com/louisgeisler/Doc2Map
110
+
111
+ <iframe src="../../getting_started/visualization/hierarchical_documents.html"
112
+ style="width:1000px; height: 770px; border: 0px;""></iframe>
113
+ """
114
+ topic_per_doc = topic_model.topics_
115
+
116
+ # Sample the data to optimize for visualization and dimensionality reduction
117
+ if sample is None or sample > 1:
118
+ sample = 1
119
+
120
+ indices = []
121
+ for topic in set(topic_per_doc):
122
+ s = np.where(np.array(topic_per_doc) == topic)[0]
123
+ size = len(s) if len(s) < 100 else int(len(s)*sample)
124
+ indices.extend(np.random.choice(s, size=size, replace=False))
125
+ indices = np.array(indices)
126
+
127
+ df = pd.DataFrame({"topic": np.array(topic_per_doc)[indices]})
128
+ df["doc"] = [docs[index] for index in indices]
129
+ df["topic"] = [topic_per_doc[index] for index in indices]
130
+
131
+ # Extract embeddings if not already done
132
+ if sample is None:
133
+ if embeddings is None and reduced_embeddings is None:
134
+ embeddings_to_reduce = topic_model._extract_embeddings(df.doc.to_list(), method="document")
135
+ else:
136
+ embeddings_to_reduce = embeddings
137
+ else:
138
+ if embeddings is not None:
139
+ embeddings_to_reduce = embeddings[indices]
140
+ elif embeddings is None and reduced_embeddings is None:
141
+ embeddings_to_reduce = topic_model._extract_embeddings(df.doc.to_list(), method="document")
142
+
143
+ # Reduce input embeddings
144
+ if reduced_embeddings is None:
145
+ umap_model = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit(embeddings_to_reduce)
146
+ embeddings_2d = umap_model.embedding_
147
+ elif sample is not None and reduced_embeddings is not None:
148
+ embeddings_2d = reduced_embeddings[indices]
149
+ elif sample is None and reduced_embeddings is not None:
150
+ embeddings_2d = reduced_embeddings
151
+
152
+ # Combine data
153
+ df["x"] = embeddings_2d[:, 0]
154
+ df["y"] = embeddings_2d[:, 1]
155
+
156
+ # Create topic list for each level, levels are created by calculating the distance
157
+ distances = hierarchical_topics.Distance.to_list()
158
+ if level_scale == 'log' or level_scale == 'logarithmic':
159
+ log_indices = np.round(np.logspace(start=math.log(1,10), stop=math.log(len(distances)-1,10), num=nr_levels)).astype(int).tolist()
160
+ log_indices.reverse()
161
+ max_distances = [distances[i] for i in log_indices]
162
+ elif level_scale == 'lin' or level_scale == 'linear':
163
+ max_distances = [distances[indices[-1]] for indices in np.array_split(range(len(hierarchical_topics)), nr_levels)][::-1]
164
+ else:
165
+ raise ValueError("level_scale needs to be one of 'log' or 'linear'")
166
+
167
+ for index, max_distance in enumerate(max_distances):
168
+
169
+ # Get topics below `max_distance`
170
+ mapping = {topic: topic for topic in df.topic.unique()}
171
+ selection = hierarchical_topics.loc[hierarchical_topics.Distance <= max_distance, :]
172
+ selection.Parent_ID = selection.Parent_ID.astype(int)
173
+ selection = selection.sort_values("Parent_ID")
174
+
175
+ for row in selection.iterrows():
176
+ for topic in row[1].Topics:
177
+ mapping[topic] = row[1].Parent_ID
178
+
179
+ # Make sure the mappings are mapped 1:1
180
+ mappings = [True for _ in mapping]
181
+ while any(mappings):
182
+ for i, (key, value) in enumerate(mapping.items()):
183
+ if value in mapping.keys() and key != value:
184
+ mapping[key] = mapping[value]
185
+ else:
186
+ mappings[i] = False
187
+
188
+ # Create new column
189
+ df[f"level_{index+1}"] = df.topic.map(mapping)
190
+ df[f"level_{index+1}"] = df[f"level_{index+1}"].astype(int)
191
+
192
+ # Prepare topic names of original and merged topics
193
+ trace_names = []
194
+ topic_names = {}
195
+ for topic in range(hierarchical_topics.Parent_ID.astype(int).max()):
196
+ if topic < hierarchical_topics.Parent_ID.astype(int).min():
197
+ if topic_model.get_topic(topic):
198
+ if isinstance(custom_labels, str):
199
+ trace_name = f"{topic}_" + "_".join(list(zip(*topic_model.topic_aspects_[custom_labels][topic]))[0][:3])
200
+ elif topic_model.custom_labels_ is not None and custom_labels:
201
+ trace_name = topic_model.custom_labels_[topic + topic_model._outliers]
202
+ else:
203
+ trace_name = f"{topic}_" + "_".join([word[:20] for word, _ in topic_model.get_topic(topic)][:3])
204
+ topic_names[topic] = {"trace_name": trace_name[:40], "plot_text": trace_name[:40]}
205
+ trace_names.append(trace_name)
206
+ else:
207
+ trace_name = f"{topic}_" + hierarchical_topics.loc[hierarchical_topics.Parent_ID == str(topic), "Parent_Name"].values[0]
208
+ plot_text = "_".join([name[:20] for name in trace_name.split("_")[:3]])
209
+ topic_names[topic] = {"trace_name": trace_name[:40], "plot_text": plot_text[:40]}
210
+ trace_names.append(trace_name)
211
+
212
+ # Prepare traces
213
+ all_traces = []
214
+ for level in range(len(max_distances)):
215
+ traces = []
216
+
217
+ # Outliers
218
+ if topic_model._outliers:
219
+ traces.append(
220
+ go.Scattergl(
221
+ x=df.loc[(df[f"level_{level+1}"] == -1), "x"],
222
+ y=df.loc[df[f"level_{level+1}"] == -1, "y"],
223
+ mode='markers+text',
224
+ name="other",
225
+ hoverinfo="text",
226
+ hovertext=df.loc[(df[f"level_{level+1}"] == -1), "doc"] if not hide_document_hover else None,
227
+ showlegend=False,
228
+ marker=dict(color='#CFD8DC', size=5, opacity=0.5)
229
+ )
230
+ )
231
+
232
+ # Selected topics
233
+ if topics:
234
+ selection = df.loc[(df.topic.isin(topics)), :]
235
+ unique_topics = sorted([int(topic) for topic in selection[f"level_{level+1}"].unique()])
236
+ else:
237
+ unique_topics = sorted([int(topic) for topic in df[f"level_{level+1}"].unique()])
238
+
239
+ for topic in unique_topics:
240
+ if topic != -1:
241
+ if topics:
242
+ selection = df.loc[(df[f"level_{level+1}"] == topic) &
243
+ (df.topic.isin(topics)), :]
244
+ else:
245
+ selection = df.loc[df[f"level_{level+1}"] == topic, :]
246
+
247
+ if not hide_annotations:
248
+ selection.loc[len(selection), :] = None
249
+ selection["text"] = ""
250
+ selection.loc[len(selection) - 1, "x"] = selection.x.mean()
251
+ selection.loc[len(selection) - 1, "y"] = selection.y.mean()
252
+ selection.loc[len(selection) - 1, "text"] = topic_names[int(topic)]["plot_text"]
253
+
254
+ traces.append(
255
+ go.Scattergl(
256
+ x=selection.x,
257
+ y=selection.y,
258
+ text=selection.text if not hide_annotations else None,
259
+ hovertext=selection.doc if not hide_document_hover else None,
260
+ hoverinfo="text",
261
+ name=topic_names[int(topic)]["trace_name"],
262
+ mode='markers+text',
263
+ marker=dict(size=5, opacity=0.5)
264
+ )
265
+ )
266
+
267
+ all_traces.append(traces)
268
+
269
+ # Track and count traces
270
+ nr_traces_per_set = [len(traces) for traces in all_traces]
271
+ trace_indices = [(0, nr_traces_per_set[0])]
272
+ for index, nr_traces in enumerate(nr_traces_per_set[1:]):
273
+ start = trace_indices[index][1]
274
+ end = nr_traces + start
275
+ trace_indices.append((start, end))
276
+
277
+ # Visualization
278
+ fig = go.Figure()
279
+ for traces in all_traces:
280
+ for trace in traces:
281
+ fig.add_trace(trace)
282
+
283
+ for index in range(len(fig.data)):
284
+ if index >= nr_traces_per_set[0]:
285
+ fig.data[index].visible = False
286
+
287
+ # Create and add slider
288
+ steps = []
289
+ for index, indices in enumerate(trace_indices):
290
+ step = dict(
291
+ method="update",
292
+ label=str(index),
293
+ args=[{"visible": [False] * len(fig.data)}]
294
+ )
295
+ for index in range(indices[1]-indices[0]):
296
+ step["args"][0]["visible"][index+indices[0]] = True
297
+ steps.append(step)
298
+
299
+ sliders = [dict(
300
+ currentvalue={"prefix": "Level: "},
301
+ pad={"t": 20},
302
+ steps=steps
303
+ )]
304
+
305
+ # Add grid in a 'plus' shape
306
+ x_range = (df.x.min() - abs((df.x.min()) * .15), df.x.max() + abs((df.x.max()) * .15))
307
+ y_range = (df.y.min() - abs((df.y.min()) * .15), df.y.max() + abs((df.y.max()) * .15))
308
+ fig.add_shape(type="line",
309
+ x0=sum(x_range) / 2, y0=y_range[0], x1=sum(x_range) / 2, y1=y_range[1],
310
+ line=dict(color="#CFD8DC", width=2))
311
+ fig.add_shape(type="line",
312
+ x0=x_range[0], y0=sum(y_range) / 2, x1=x_range[1], y1=sum(y_range) / 2,
313
+ line=dict(color="#9E9E9E", width=2))
314
+ fig.add_annotation(x=x_range[0], y=sum(y_range) / 2, text="D1", showarrow=False, yshift=10)
315
+ fig.add_annotation(y=y_range[1], x=sum(x_range) / 2, text="D2", showarrow=False, xshift=10)
316
+
317
+ # Stylize layout
318
+ fig.update_layout(
319
+ sliders=sliders,
320
+ template="simple_white",
321
+ title={
322
+ 'text': f"{title}",
323
+ 'x': 0.5,
324
+ 'xanchor': 'center',
325
+ 'yanchor': 'top',
326
+ 'font': dict(
327
+ size=22,
328
+ color="Black")
329
+ },
330
+ width=width,
331
+ height=height,
332
+ )
333
+
334
+ fig.update_xaxes(visible=False)
335
+ fig.update_yaxes(visible=False)
336
+ return fig
funcs/bertopic_hierarchical_documents_to_df.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import plotly.graph_objects as go
4
+ import math
5
+
6
+ from umap import UMAP
7
+ from typing import List, Union
8
+
9
+
10
+ def visualize_hierarchical_documents_to_df(topic_model,
11
+ docs: List[str],
12
+ hierarchical_topics: pd.DataFrame,
13
+ topics: List[int] = None,
14
+ embeddings: np.ndarray = None,
15
+ reduced_embeddings: np.ndarray = None,
16
+ sample: Union[float, int] = None,
17
+ hide_annotations: bool = False,
18
+ hide_document_hover: bool = True,
19
+ nr_levels: int = 10,
20
+ level_scale: str = 'linear',
21
+ custom_labels: Union[bool, str] = False,
22
+ title: str = "<b>Hierarchical Documents and Topics</b>",
23
+ width: int = 1200,
24
+ height: int = 750) -> go.Figure:
25
+ """ Visualize documents and their topics in 2D at different levels of hierarchy
26
+
27
+ Arguments:
28
+ docs: The documents you used when calling either `fit` or `fit_transform`
29
+ hierarchical_topics: A dataframe that contains a hierarchy of topics
30
+ represented by their parents and their children
31
+ topics: A selection of topics to visualize.
32
+ Not to be confused with the topics that you get from `.fit_transform`.
33
+ For example, if you want to visualize only topics 1 through 5:
34
+ `topics = [1, 2, 3, 4, 5]`.
35
+ embeddings: The embeddings of all documents in `docs`.
36
+ reduced_embeddings: The 2D reduced embeddings of all documents in `docs`.
37
+ sample: The percentage of documents in each topic that you would like to keep.
38
+ Value can be between 0 and 1. Setting this value to, for example,
39
+ 0.1 (10% of documents in each topic) makes it easier to visualize
40
+ millions of documents as a subset is chosen.
41
+ hide_annotations: Hide the names of the traces on top of each cluster.
42
+ hide_document_hover: Hide the content of the documents when hovering over
43
+ specific points. Helps to speed up generation of visualizations.
44
+ nr_levels: The number of levels to be visualized in the hierarchy. First, the distances
45
+ in `hierarchical_topics.Distance` are split in `nr_levels` lists of distances.
46
+ Then, for each list of distances, the merged topics are selected that have a
47
+ distance less or equal to the maximum distance of the selected list of distances.
48
+ NOTE: To get all possible merged steps, make sure that `nr_levels` is equal to
49
+ the length of `hierarchical_topics`.
50
+ level_scale: Whether to apply a linear or logarithmic (log) scale levels of the distance
51
+ vector. Linear scaling will perform an equal number of merges at each level
52
+ while logarithmic scaling will perform more mergers in earlier levels to
53
+ provide more resolution at higher levels (this can be used for when the number
54
+ of topics is large).
55
+ custom_labels: If bool, whether to use custom topic labels that were defined using
56
+ `topic_model.set_topic_labels`.
57
+ If `str`, it uses labels from other aspects, e.g., "Aspect1".
58
+ NOTE: Custom labels are only generated for the original
59
+ un-merged topics.
60
+ title: Title of the plot.
61
+ width: The width of the figure.
62
+ height: The height of the figure.
63
+
64
+ Examples:
65
+
66
+ To visualize the topics simply run:
67
+
68
+ ```python
69
+ topic_model.visualize_hierarchical_documents(docs, hierarchical_topics)
70
+ ```
71
+
72
+ Do note that this re-calculates the embeddings and reduces them to 2D.
73
+ The advised and prefered pipeline for using this function is as follows:
74
+
75
+ ```python
76
+ from sklearn.datasets import fetch_20newsgroups
77
+ from sentence_transformers import SentenceTransformer
78
+ from bertopic import BERTopic
79
+ from umap import UMAP
80
+
81
+ # Prepare embeddings
82
+ docs = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))['data']
83
+ sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
84
+ embeddings = sentence_model.encode(docs, show_progress_bar=False)
85
+
86
+ # Train BERTopic and extract hierarchical topics
87
+ topic_model = BERTopic().fit(docs, embeddings)
88
+ hierarchical_topics = topic_model.hierarchical_topics(docs)
89
+
90
+ # Reduce dimensionality of embeddings, this step is optional
91
+ # reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings)
92
+
93
+ # Run the visualization with the original embeddings
94
+ topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, embeddings=embeddings)
95
+
96
+ # Or, if you have reduced the original embeddings already:
97
+ topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)
98
+ ```
99
+
100
+ Or if you want to save the resulting figure:
101
+
102
+ ```python
103
+ fig = topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)
104
+ fig.write_html("path/to/file.html")
105
+ ```
106
+
107
+ NOTE:
108
+ This visualization was inspired by the scatter plot representation of Doc2Map:
109
+ https://github.com/louisgeisler/Doc2Map
110
+
111
+ <iframe src="../../getting_started/visualization/hierarchical_documents.html"
112
+ style="width:1000px; height: 770px; border: 0px;""></iframe>
113
+ """
114
+ topic_per_doc = topic_model.topics_
115
+
116
+ # Sample the data to optimize for visualization and dimensionality reduction
117
+ if sample is None or sample > 1:
118
+ sample = 1
119
+
120
+ indices = []
121
+ for topic in set(topic_per_doc):
122
+ s = np.where(np.array(topic_per_doc) == topic)[0]
123
+ size = len(s) if len(s) < 100 else int(len(s)*sample)
124
+ indices.extend(np.random.choice(s, size=size, replace=False))
125
+ indices = np.array(indices)
126
+
127
+ df = pd.DataFrame({"topic": np.array(topic_per_doc)[indices]})
128
+ df["doc"] = [docs[index] for index in indices]
129
+ df["topic"] = [topic_per_doc[index] for index in indices]
130
+
131
+ # Extract embeddings if not already done
132
+ if sample is None:
133
+ if embeddings is None and reduced_embeddings is None:
134
+ embeddings_to_reduce = topic_model._extract_embeddings(df.doc.to_list(), method="document")
135
+ else:
136
+ embeddings_to_reduce = embeddings
137
+ else:
138
+ if embeddings is not None:
139
+ embeddings_to_reduce = embeddings[indices]
140
+ elif embeddings is None and reduced_embeddings is None:
141
+ embeddings_to_reduce = topic_model._extract_embeddings(df.doc.to_list(), method="document")
142
+
143
+ # Reduce input embeddings
144
+ if reduced_embeddings is None:
145
+ umap_model = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit(embeddings_to_reduce)
146
+ embeddings_2d = umap_model.embedding_
147
+ elif sample is not None and reduced_embeddings is not None:
148
+ embeddings_2d = reduced_embeddings[indices]
149
+ elif sample is None and reduced_embeddings is not None:
150
+ embeddings_2d = reduced_embeddings
151
+
152
+ # Combine data
153
+ df["x"] = embeddings_2d[:, 0]
154
+ df["y"] = embeddings_2d[:, 1]
155
+
156
+ # Create topic list for each level, levels are created by calculating the distance
157
+ distances = hierarchical_topics.Distance.to_list()
158
+ if level_scale == 'log' or level_scale == 'logarithmic':
159
+ log_indices = np.round(np.logspace(start=math.log(1,10), stop=math.log(len(distances)-1,10), num=nr_levels)).astype(int).tolist()
160
+ log_indices.reverse()
161
+ max_distances = [distances[i] for i in log_indices]
162
+ elif level_scale == 'lin' or level_scale == 'linear':
163
+ max_distances = [distances[indices[-1]] for indices in np.array_split(range(len(hierarchical_topics)), nr_levels)][::-1]
164
+ else:
165
+ raise ValueError("level_scale needs to be one of 'log' or 'linear'")
166
+
167
+ for index, max_distance in enumerate(max_distances):
168
+
169
+ # Get topics below `max_distance`
170
+ mapping = {topic: topic for topic in df.topic.unique()}
171
+ selection = hierarchical_topics.loc[hierarchical_topics.Distance <= max_distance, :]
172
+ selection.Parent_ID = selection.Parent_ID.astype(int)
173
+ selection = selection.sort_values("Parent_ID")
174
+
175
+ for row in selection.iterrows():
176
+ for topic in row[1].Topics:
177
+ mapping[topic] = row[1].Parent_ID
178
+
179
+ # Make sure the mappings are mapped 1:1
180
+ mappings = [True for _ in mapping]
181
+ while any(mappings):
182
+ for i, (key, value) in enumerate(mapping.items()):
183
+ if value in mapping.keys() and key != value:
184
+ mapping[key] = mapping[value]
185
+ else:
186
+ mappings[i] = False
187
+
188
+ # Create new column
189
+ df[f"level_{index+1}"] = df.topic.map(mapping)
190
+ df[f"level_{index+1}"] = df[f"level_{index+1}"].astype(int)
191
+
192
+ # Prepare topic names of original and merged topics
193
+ trace_names = []
194
+ topic_names = {}
195
+ for topic in range(hierarchical_topics.Parent_ID.astype(int).max()):
196
+ if topic < hierarchical_topics.Parent_ID.astype(int).min():
197
+ if topic_model.get_topic(topic):
198
+ if isinstance(custom_labels, str):
199
+ trace_name = f"{topic}_" + "_".join(list(zip(*topic_model.topic_aspects_[custom_labels][topic]))[0][:3])
200
+ elif topic_model.custom_labels_ is not None and custom_labels:
201
+ trace_name = topic_model.custom_labels_[topic + topic_model._outliers]
202
+ else:
203
+ trace_name = f"{topic}_" + "_".join([word[:20] for word, _ in topic_model.get_topic(topic)][:3])
204
+ topic_names[topic] = {"trace_name": trace_name[:40], "plot_text": trace_name[:40]}
205
+ trace_names.append(trace_name)
206
+ else:
207
+ trace_name = f"{topic}_" + hierarchical_topics.loc[hierarchical_topics.Parent_ID == str(topic), "Parent_Name"].values[0]
208
+ plot_text = "_".join([name[:20] for name in trace_name.split("_")[:3]])
209
+ topic_names[topic] = {"trace_name": trace_name[:40], "plot_text": plot_text[:40]}
210
+ trace_names.append(trace_name)
211
+
212
+ # Prepare traces
213
+ all_traces = []
214
+ for level in range(len(max_distances)):
215
+ traces = []
216
+
217
+ # Selected topics
218
+ if topics:
219
+ selection = df.loc[(df.topic.isin(topics)), :]
220
+ unique_topics = sorted([int(topic) for topic in selection[f"level_{level+1}"].unique()])
221
+ else:
222
+ unique_topics = sorted([int(topic) for topic in df[f"level_{level+1}"].unique()])
223
+
224
+ for topic in unique_topics:
225
+ if topic != -1:
226
+ if topics:
227
+ selection = df.loc[(df[f"level_{level+1}"] == topic) &
228
+ (df.topic.isin(topics)), :]
229
+ else:
230
+ selection = df.loc[df[f"level_{level+1}"] == topic, :]
231
+
232
+ if not hide_annotations:
233
+ selection.loc[len(selection), :] = None
234
+ selection["text"] = ""
235
+ selection.loc[len(selection) - 1, "x"] = selection.x.mean()
236
+ selection.loc[len(selection) - 1, "y"] = selection.y.mean()
237
+ selection.loc[len(selection) - 1, "text"] = topic_names[int(topic)]["plot_text"]
238
+
239
+ all_traces.append(traces)
240
+
241
+ # Track and count traces
242
+ nr_traces_per_set = [len(traces) for traces in all_traces]
243
+ trace_indices = [(0, nr_traces_per_set[0])]
244
+ for index, nr_traces in enumerate(nr_traces_per_set[1:]):
245
+ start = trace_indices[index][1]
246
+ end = nr_traces + start
247
+ trace_indices.append((start, end))
248
+
249
+
250
+ return all_traces, selection, df
funcs/representation_model.py CHANGED
@@ -129,7 +129,7 @@ def find_model_file(hf_model_name, hf_model_file, search_folder):
129
 
130
  print("Downloading model to: ", hf_home_value)
131
 
132
- hf_hub_download(repo_id=hf_model_name, filename='phi-2-orange.Q5_K_M.gguf', cache_dir=hf_home_value)
133
 
134
  found_file = find_file(hf_home_value, file_to_find)
135
  return found_file
@@ -141,7 +141,7 @@ def create_representation_model(create_llm_topic_labels, llm_config, hf_model_na
141
  # Use llama.cpp to load in model
142
 
143
  # This was for testing on systems without a HF_HOME env variable
144
- os.unsetenv("HF_HOME")
145
 
146
  #if "HF_HOME" in os.environ:
147
  # del os.environ["HF_HOME"]
@@ -168,7 +168,7 @@ def create_representation_model(create_llm_topic_labels, llm_config, hf_model_na
168
  # All representation models
169
  representation_model = {
170
  "KeyBERT": keybert,
171
- "Phi": llm_model
172
  }
173
 
174
  elif create_llm_topic_labels == "No":
 
129
 
130
  print("Downloading model to: ", hf_home_value)
131
 
132
+ hf_hub_download(repo_id=hf_model_name, filename=hf_model_file, cache_dir=hf_home_value)
133
 
134
  found_file = find_file(hf_home_value, file_to_find)
135
  return found_file
 
141
  # Use llama.cpp to load in model
142
 
143
  # This was for testing on systems without a HF_HOME env variable
144
+ #os.unsetenv("HF_HOME")
145
 
146
  #if "HF_HOME" in os.environ:
147
  # del os.environ["HF_HOME"]
 
168
  # All representation models
169
  representation_model = {
170
  "KeyBERT": keybert,
171
+ "LLM": llm_model
172
  }
173
 
174
  elif create_llm_topic_labels == "No":