File size: 30,025 Bytes
5d87c3c
b4510a6
 
 
 
9dbf344
 
 
 
aa3df37
be094ee
 
9dbf344
4cfed8e
 
 
9dbf344
ff32b4a
9dbf344
 
 
b4510a6
ff32b4a
 
9dbf344
b4510a6
 
 
9dbf344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4510a6
9dbf344
 
 
 
 
b4510a6
4cfed8e
9dbf344
 
5d87c3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfed8e
9dbf344
b4510a6
9dbf344
b4510a6
9dbf344
 
5d87c3c
be094ee
 
9dbf344
5d87c3c
b4510a6
 
9dbf344
b4510a6
ffe5eb2
 
 
b4510a6
 
 
 
 
 
 
 
ffe5eb2
b4510a6
9eeba1e
aa3df37
 
ff32b4a
5d87c3c
9dbf344
 
 
b4510a6
9dbf344
 
ffe5eb2
e09dd3b
5d87c3c
 
 
 
 
ff32b4a
9dbf344
b4510a6
 
e09dd3b
 
 
5d87c3c
 
9dbf344
4cfed8e
 
 
be094ee
4cfed8e
be094ee
b4510a6
 
be094ee
 
 
 
 
 
4cfed8e
e09dd3b
 
aa3df37
4cfed8e
43ac0d8
 
4cfed8e
 
ff32b4a
4cfed8e
 
 
43ac0d8
aa3df37
b4510a6
aa3df37
e09dd3b
b4510a6
 
 
 
 
 
5d87c3c
ffe5eb2
9dbf344
 
aa3df37
be094ee
ffe5eb2
 
 
 
b4510a6
 
ffe5eb2
9dbf344
b4510a6
1f1a1c7
b4510a6
1f1a1c7
b4510a6
 
 
 
9dbf344
 
ff32b4a
 
 
 
 
 
b4510a6
ff32b4a
4cfed8e
 
9dbf344
b4510a6
 
be094ee
ffe5eb2
 
 
 
 
0fe5421
b4510a6
 
ffe5eb2
9dbf344
b4510a6
9dbf344
b4510a6
 
 
 
be094ee
b4510a6
be094ee
b4510a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffe5eb2
5d87c3c
 
 
 
 
 
 
 
 
 
be094ee
5d87c3c
be094ee
5d87c3c
 
 
 
 
 
 
 
 
b4510a6
ffe5eb2
b4510a6
 
 
5d87c3c
 
 
 
 
b4510a6
5d87c3c
b4510a6
 
5d87c3c
 
 
b4510a6
5d87c3c
9dbf344
ffe5eb2
5d87c3c
 
 
b4510a6
5d87c3c
 
 
 
b4510a6
 
 
 
 
ffe5eb2
9dbf344
 
5d87c3c
1f1a1c7
 
5d87c3c
 
 
 
 
b4510a6
5d87c3c
 
 
 
 
 
b4510a6
5d87c3c
b4510a6
5d87c3c
 
 
 
9dbf344
5d87c3c
 
 
 
b4510a6
5d87c3c
 
 
b4510a6
5d87c3c
 
 
b4510a6
9dbf344
4cfed8e
1f1a1c7
 
4cfed8e
5d87c3c
b4510a6
 
 
 
 
 
 
 
 
4cfed8e
 
9dbf344
b4510a6
 
5d87c3c
4cfed8e
5d87c3c
 
 
4cfed8e
b4510a6
 
 
 
 
4cfed8e
5d87c3c
 
4cfed8e
b4510a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dbf344
5d87c3c
43ac0d8
b4510a6
1f1a1c7
 
5d87c3c
 
 
e0f53cc
5d87c3c
 
 
 
 
 
 
 
 
 
 
 
 
 
b4510a6
e0f53cc
b4510a6
ffe5eb2
 
81f1b56
b4510a6
 
 
 
 
 
5d87c3c
b4510a6
 
 
 
 
 
 
5d87c3c
b4510a6
 
 
 
 
 
 
 
 
 
aa3df37
5d87c3c
 
 
aa3df37
5d87c3c
 
 
4cfed8e
aa3df37
5d87c3c
aa3df37
 
b4510a6
 
 
 
 
 
 
 
9dbf344
5d87c3c
 
b4510a6
5d87c3c
 
 
 
 
 
 
 
 
 
 
 
 
b4510a6
 
5d87c3c
9dbf344
 
 
 
 
 
9eeba1e
5d87c3c
 
 
b4510a6
9dbf344
 
 
ff32b4a
be094ee
ffe5eb2
 
9dbf344
ff32b4a
9dbf344
 
 
 
b4510a6
9dbf344
ff32b4a
 
0fe5421
 
9dbf344
fac3624
e09dd3b
9dbf344
 
 
 
 
5d87c3c
9dbf344
 
5d87c3c
 
 
 
b4510a6
5d87c3c
731ed23
5d87c3c
 
b4510a6
 
 
 
6622531
b4510a6
 
 
 
 
 
9dbf344
ff32b4a
 
4cfed8e
 
 
b4510a6
 
4cfed8e
aa3df37
b4510a6
81f1b56
9dbf344
 
b4510a6
9dbf344
 
b4510a6
 
 
5d87c3c
b4510a6
5d87c3c
b4510a6
5d87c3c
b4510a6
5d87c3c
731ed23
9dbf344
 
 
5d87c3c
 
 
 
 
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import os

# Dendrograms will not work with the latest version of scipy (1.12.0), so installing the version prior to be safe
os.system("pip install scipy==1.11.4")

import gradio as gr
from datetime import datetime
import pandas as pd
import numpy as np
import time

from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
import funcs.anonymiser as anon
from umap import UMAP

from torch import cuda, backends, version

# Default seed, can be changed in number selection on options page
random_seed = 42

# Check for torch cuda
# If you want to disable cuda for testing purposes
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

print("Is CUDA enabled? ", cuda.is_available())
print("Is a CUDA device available on this computer?", backends.cudnn.enabled)
if cuda.is_available():
    torch_device = "gpu"
    print("Cuda version installed is: ", version.cuda)
    low_resource_mode = "No"
    #os.system("nvidia-smi")
else: 
    torch_device =  "cpu"
    low_resource_mode = "Yes"

print("Device used is: ", torch_device)



from bertopic import BERTopic


today = datetime.now().strftime("%d%m%Y")
today_rev = datetime.now().strftime("%Y%m%d")

from funcs.helper_functions import dummy_function, initial_file_load, read_file, zip_folder, delete_files_in_folder, save_topic_outputs
#from funcs.representation_model import representation_model
from funcs.embeddings import make_or_load_embeddings

# Log terminal output: https://github.com/gradio-app/gradio/issues/2362
import sys

class Logger:
    def __init__(self, filename):
        self.terminal = sys.stdout
        self.log = open(filename, "w")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
        
    def flush(self):
        self.terminal.flush()
        self.log.flush()
        
    def isatty(self):
        return False    

sys.stdout = Logger("output.log")

def read_logs():
    sys.stdout.flush()
    with open("output.log", "r") as f:
        return f.read()

# Load embeddings
embeddings_name = "BAAI/bge-small-en-v1.5" #"jinaai/jina-embeddings-v2-base-en"

# Use of Jina deprecated - kept here for posterity
# Pinning a Jina revision for security purposes: https://www.baseten.co/blog/pinning-ml-model-revisions-for-compatibility-and-security/
# Save Jina model locally as described here: https://huggingface.co/jinaai/jina-embeddings-v2-base-en/discussions/29
# local_embeddings_location = "model/jina/"
#revision_choice = "b811f03af3d4d7ea72a7c25c802b21fc675a5d99"
#revision_choice = "69d43700292701b06c24f43b96560566a4e5ad1f"

# Model used for representing topics
hf_model_name =  'second-state/stablelm-2-zephyr-1.6b-GGUF' #'TheBloke/phi-2-orange-GGUF' #'NousResearch/Nous-Capybara-7B-V1.9-GGUF'
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'

def extract_topics(data, in_files, min_docs_slider, in_colnames, max_topics_slider, candidate_topics, data_file_name_no_ext, custom_labels_df, anonymise_drop, return_intermediate_files, embeddings_super_compress, low_resource_mode, save_topic_model, embeddings_out, zero_shot_similarity, random_seed, calc_probs, progress=gr.Progress(track_tqdm=True)):

    progress(0, desc= "Loading data")

    if calc_probs == "No":
        calc_probs = False
    elif calc_probs == "Yes":
        print("Calculating all probabilities.")
        calc_probs == True

    if not in_colnames:
        error_message = "Please enter one column name to use to find topics."
        print(error_message)
        return error_message, None, embeddings_out, data_file_name_no_ext, None, None

    all_tic = time.perf_counter()

    output_list = []
    file_list = [string.name for string in in_files]

    in_colnames_list_first = in_colnames[0]

    docs = list(data[in_colnames_list_first].str.lower())
    
    if anonymise_drop == "Yes":
        progress(0.1, desc= "Anonymising data")
        anon_tic = time.perf_counter()
        
        data_anon_col, anonymisation_success = anon.anonymise_script(data, in_colnames_list_first, anon_strat="replace")
        data[in_colnames_list_first] = data_anon_col[in_colnames_list_first]
        anonymise_data_name = data_file_name_no_ext + "_anonymised_" + today_rev +  ".csv"
        data.to_csv(anonymise_data_name)
        output_list.append(anonymise_data_name)

        print(anonymisation_success)

        anon_toc = time.perf_counter()
        time_out = f"Anonymising text took {anon_toc - anon_tic:0.1f} seconds"

    # Check if embeddings are being loaded in 
    progress(0.2, desc= "Loading/creating embeddings")

    print("Low resource mode: ", low_resource_mode)

    if low_resource_mode == "No":
        print("Using high resource BGE transformer model")

        embedding_model = SentenceTransformer(embeddings_name)

        # Use of Jina now superseded by BGE, keeping this code just in case I consider reverting one day
        #try:
        #embedding_model = AutoModel.from_pretrained(embeddings_name, revision = revision_choice, trust_remote_code=True,device_map="auto") # For Jina
        #except:
        #     embedding_model = AutoModel.from_pretrained(embeddings_name)#, revision = revision_choice, trust_remote_code=True, device_map="auto", use_auth_token=os.environ["HF_TOKEN"])
        #tokenizer = AutoTokenizer.from_pretrained(embeddings_name)
        #embedding_model_pipe = pipeline("feature-extraction", model=embedding_model, tokenizer=tokenizer)

        # UMAP model uses Bertopic defaults
        umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', low_memory=False, random_state=random_seed)

    elif low_resource_mode == "Yes":
        print("Choosing low resource TF-IDF model.")

        embedding_model_pipe = make_pipeline(
                TfidfVectorizer(),
                TruncatedSVD(100) # 100 # To be compatible with zero shot, this needs to be lower than number of suggested topics
                )
        embedding_model = embedding_model_pipe

        umap_model = TruncatedSVD(n_components=5, random_state=random_seed)

    embeddings_out = make_or_load_embeddings(docs, file_list, embeddings_out, embedding_model, embeddings_super_compress, low_resource_mode)

    vectoriser_model = CountVectorizer(stop_words="english", ngram_range=(1, 2), min_df=0.1)

    # Representation model not currently used in this function
    #print("Create Keybert-like topic representations by default")
    #from funcs.representation_model import create_representation_model, llm_config, chosen_start_tag
    #representation_model = create_representation_model("No", llm_config, hf_model_name, hf_model_file, chosen_start_tag, low_resource_mode)  

 
    progress(0.3, desc= "Embeddings loaded. Creating BERTopic model")

    if not candidate_topics:
        
        topic_model = BERTopic( embedding_model=embedding_model, #embedding_model_pipe, #for Jina
                                vectorizer_model=vectoriser_model,
                                umap_model=umap_model,
                                min_topic_size = min_docs_slider,
                                nr_topics = max_topics_slider,
                                calculate_probabilities=calc_probs,
                                #representation_model=representation_model,
                                verbose = True)

        assigned_topics, probs = topic_model.fit_transform(docs, embeddings_out)

        #print(assigned_topics)

        # Replace original labels with Keybert labels
        #if "KeyBERT" in topic_model.get_topic_info().columns:
        #    keybert_labels = [f"{i+1}: {', '.join(entry[:5])}" for i, entry in enumerate(topic_model.get_topics(full=True)["KeyBERT"].values())]
        #    topic_model.set_topic_labels(keybert_labels)


    # Do this if you have pre-defined topics
    else:
        if low_resource_mode == "Yes":
            error_message = "Zero shot topic modelling currently not compatible with low-resource embeddings. Please change this option to 'No' on the options tab and retry."
            print(error_message)

            return error_message, output_list, embeddings_out, data_file_name_no_ext, None, docs

        zero_shot_topics = read_file(candidate_topics.name)
        zero_shot_topics_lower = list(zero_shot_topics.iloc[:, 0].str.lower())

 

        topic_model = BERTopic( embedding_model=embedding_model, #embedding_model_pipe, # for Jina
                                vectorizer_model=vectoriser_model,
                                umap_model=umap_model,
                                min_topic_size = min_docs_slider,
                                nr_topics = max_topics_slider,
                                zeroshot_topic_list = zero_shot_topics_lower,
                                zeroshot_min_similarity = zero_shot_similarity, # 0.7
                                calculate_probabilities=calc_probs,
                                #representation_model=representation_model,
                                verbose = True)
        
        assigned_topics, probs = topic_model.fit_transform(docs, embeddings_out)

        # For some reason, zero topic modelling exports assigned topics as a np.array instead of a list. Converting it back here.
        if isinstance(assigned_topics, np.ndarray):
            assigned_topics = assigned_topics.tolist()
        #print(assigned_topics.tolist())

         # Zero shot modelling is a model merge, which wipes the c_tf_idf part of the resulting model completely. To get hierarchical modelling to work, we need to recreate this part of the model with the CountVectorizer options used to create the initial model. Since with zero shot, we are merging two models that have exactly the same set of documents, the vocubulary should be the same, and so recreating the cf_tf_idf component in this way shouldn't be a problem. Discussion here, and below based on Maarten's suggested code: https://github.com/MaartenGr/BERTopic/issues/1700

        doc_dets = topic_model.get_document_info(docs)

        documents_per_topic = doc_dets.groupby(['Topic'], as_index=False).agg({'Document': ' '.join})

        # Assign CountVectorizer to merged model

        topic_model.vectorizer_model = vectoriser_model

        # Re-calculate c-TF-IDF
        c_tf_idf, _ = topic_model._c_tf_idf(documents_per_topic)
        topic_model.c_tf_idf_ = c_tf_idf

        # Replace original labels with Keybert labels
        #if "KeyBERT" in topic_model.get_topic_info().columns:
        #    print(topic_model.get_topics(full=True)["KeyBERT"].values())
        #    keybert_labels = [f"{i+1}: {', '.join(entry[:5])}" for i, entry in enumerate(topic_model.get_topics(full=True)["KeyBERT"].values())]
        #    topic_model.set_topic_labels(keybert_labels) 

    if not assigned_topics:
    # Handle the empty array case
        return "No topics found.", output_list, embeddings_out, data_file_name_no_ext, topic_model, docs
    
    else: 
        print("Topic model created.")

    if not custom_labels_df.empty:
        #print(custom_labels_df.shape)

        #topic_dets = topic_model.get_topic_info()
        #print(topic_dets.shape)

        topic_model.set_topic_labels(list(custom_labels_df.iloc[:,0]))

    # Outputs
    output_list, output_text = save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model)

     # If you want to save your embedding files
    if return_intermediate_files == "Yes":
        print("Saving embeddings to file")
        if low_resource_mode == "Yes":
            embeddings_file_name = data_file_name_no_ext + '_' + 'tfidf_embeddings.npz'
        else:
            if embeddings_super_compress == "No":
                embeddings_file_name = data_file_name_no_ext + '_' + 'bge_embeddings.npz'
            else:
                embeddings_file_name = data_file_name_no_ext + '_' + 'bge_embeddings_compress.npz'

        np.savez_compressed(embeddings_file_name, embeddings_out)

        output_list.append(embeddings_file_name)

    all_toc = time.perf_counter()
    time_out = f"All processes took {all_toc - all_tic:0.1f} seconds."
    print(time_out)

    return output_text, output_list, embeddings_out, data_file_name_no_ext, topic_model, docs

def reduce_outliers(topic_model, docs, embeddings_out, data_file_name_no_ext, save_topic_model, progress=gr.Progress(track_tqdm=True)):

    progress(0, desc= "Preparing data")

    output_list = []

    all_tic = time.perf_counter()

    assigned_topics, probs = topic_model.fit_transform(docs, embeddings_out)

    if isinstance(assigned_topics, np.ndarray):
        assigned_topics = assigned_topics.tolist()

    #progress(0.2, desc= "Loading in representation model")
    #print("Create LLM topic labels:", create_llm_topic_labels)
    #from funcs.representation_model import create_representation_model, llm_config, chosen_start_tag
    #representation_model = create_representation_model(create_llm_topic_labels, llm_config, hf_model_name, hf_model_file, chosen_start_tag, low_resource_mode)  

    # Reduce outliers if required, then update representation
    progress(0.2, desc= "Reducing outliers")
    print("Reducing outliers.")
    # Calculate the c-TF-IDF representation for each outlier document and find the best matching c-TF-IDF topic representation using cosine similarity.
    assigned_topics = topic_model.reduce_outliers(docs, assigned_topics, strategy="embeddings")
    # Then, update the topics to the ones that considered the new data

    print("Finished reducing outliers.")

    progress(0.7, desc= "Replacing topic names with LLMs if necessary")
    #print("Create LLM topic labels:", "No")
    #vectoriser_model = CountVectorizer(stop_words="english", ngram_range=(1, 2), min_df=0.1)
    #representation_model = create_representation_model("No", llm_config, hf_model_name, hf_model_file, chosen_start_tag, low_resource_mode) 
    #topic_model.update_topics(docs, topics=assigned_topics, vectorizer_model=vectoriser_model, representation_model=representation_model)

    topic_dets = topic_model.get_topic_info()

    # Replace original labels with LLM labels
    if "LLM" in topic_model.get_topic_info().columns:
        llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["LLM"].values()]
        topic_model.set_topic_labels(llm_labels)
    else:
        topic_model.set_topic_labels(list(topic_dets["Name"]))

    # Outputs   
    progress(0.9, desc= "Saving to file")
    output_list, output_text = save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model)

    all_toc = time.perf_counter()
    time_out = f"All processes took {all_toc - all_tic:0.1f} seconds"
    print(time_out)
    
    return output_text, output_list, topic_model

def represent_topics(topic_model, docs, embeddings_out, data_file_name_no_ext, low_resource_mode, save_topic_model, progress=gr.Progress(track_tqdm=True)):
    #from funcs.prompts import capybara_prompt, capybara_start, open_hermes_prompt, open_hermes_start, stablelm_prompt, stablelm_start
    from funcs.representation_model import create_representation_model, llm_config, chosen_start_tag

    output_list = []

    all_tic = time.perf_counter()

    vectoriser_model = CountVectorizer(stop_words="english", ngram_range=(1, 2), min_df=0.1)

    assigned_topics, probs = topic_model.fit_transform(docs, embeddings_out)

    topic_dets = topic_model.get_topic_info()

    progress(0.1, desc= "Loading LLM model")
    print("Create LLM topic labels:", "Yes")
    representation_model = create_representation_model("Yes", llm_config, hf_model_name, hf_model_file, chosen_start_tag, low_resource_mode)  

    topic_model.update_topics(docs, topics=assigned_topics, vectorizer_model=vectoriser_model, representation_model=representation_model)

    # Replace original labels with LLM labels
    if "LLM" in topic_model.get_topic_info().columns:
        llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["LLM"].values()]
        topic_model.set_topic_labels(llm_labels)

        label_list_file_name = data_file_name_no_ext + '_llm_topic_list_' + today_rev + '.csv'

        llm_labels_df = pd.DataFrame(data={"Label":llm_labels})
        llm_labels_df.to_csv(label_list_file_name, index=None)
        #with open(label_list_file_name, 'w') as file:
        #    file.write(f"Label\n")
        #    for item in llm_labels:
        #        file.write(f"{item}\n")
        output_list.append(label_list_file_name)
    else:
        topic_model.set_topic_labels(list(topic_dets["Name"]))

    # Outputs
    progress(0.8, desc= "Saving outputs")
    output_list, output_text = save_topic_outputs(topic_model, data_file_name_no_ext, output_list, docs, save_topic_model)

    all_toc = time.perf_counter()
    time_out = f"All processes took {all_toc - all_tic:0.1f} seconds"
    print(time_out)

    return output_text, output_list, topic_model

def visualise_topics(topic_model, data, data_file_name_no_ext, low_resource_mode,  embeddings_out, in_label, in_colnames, sample_prop, visualisation_type_radio, random_seed, progress=gr.Progress()):

    progress(0, desc= "Preparing data for visualisation")

    output_list = []
    vis_tic = time.perf_counter()

    from funcs.bertopic_vis_documents import visualize_documents_custom, visualize_hierarchical_documents_custom, visualize_barchart_custom

    if not visualisation_type_radio:
        return "Please choose a visualisation type above.", output_list, None, None

    # Get topic labels
    if in_label:
       in_label_list_first = in_label[0]
    else:
       return "Label column not found. Please enter this above.", output_list, None, None
    
    # Get docs
    if in_colnames:
        in_colnames_list_first = in_colnames[0]
    else:
        return "Label column not found. Please enter this on the data load tab.", output_list, None, None
    
    docs = list(data[in_colnames_list_first].str.lower())

    # Make sure format of input series is good
    data[in_label_list_first] = data[in_label_list_first].fillna('').astype(str)
    label_list = list(data[in_label_list_first])

    topic_dets = topic_model.get_topic_info()

    # Replace original labels with LLM labels if they exist, or go with the 'Name' column
    if "LLM" in topic_model.get_topic_info().columns:
        llm_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["LLM"].values()]
        topic_model.set_topic_labels(llm_labels)
    else:
        topic_model.set_topic_labels(list(topic_dets["Name"]))

    # Pre-reduce embeddings for visualisation purposes
    if low_resource_mode == "No":
        reduced_embeddings = UMAP(n_neighbors=15, n_components=2, min_dist=0.0, metric='cosine', random_state=random_seed).fit_transform(embeddings_out)
    else:
        reduced_embeddings = TruncatedSVD(2, random_state=random_seed).fit_transform(embeddings_out)

    progress(0.5, desc= "Creating visualisation (this can take a while)")
    # Visualise the topics:
    
    print("Creating visualisation")

    # "Topic document graph", "Hierarchical view"

    if visualisation_type_radio == "Topic document graph":
        topics_vis = visualize_documents_custom(topic_model, docs, hover_labels = label_list, reduced_embeddings=reduced_embeddings, hide_annotations=True, hide_document_hover=False, custom_labels=True, sample = sample_prop, width= 1200, height = 750)

        topics_vis_name = data_file_name_no_ext + '_' + 'vis_topic_docs_' + today_rev + '.html'
        topics_vis.write_html(topics_vis_name)
        output_list.append(topics_vis_name)

        topics_vis_2 = visualize_barchart_custom(topic_model, top_n_topics = 12, custom_labels=True, width= 300, height = 250)

        topics_vis_2_name = data_file_name_no_ext + '_' + 'vis_barchart_' + today_rev + '.html'
        topics_vis_2.write_html(topics_vis_2_name)
        output_list.append(topics_vis_2_name)

    elif visualisation_type_radio == "Hierarchical view":
       
        # Check that original topics are retained
        #new_topic_dets = topic_model.get_topic_info()
        #new_topic_dets.to_csv("new_topic_dets.csv")

        #from funcs.bertopic_hierarchical_topics_mod import hierarchical_topics_mod

        hierarchical_topics = topic_model.hierarchical_topics(docs)

        # Save new hierarchical topic model to file
        hierarchical_topics_name = data_file_name_no_ext + '_' + 'vis_hierarchy_topics_' + today_rev + '.csv'
        hierarchical_topics.to_csv(hierarchical_topics_name)
        output_list.append(hierarchical_topics_name)

        #hierarchical_topics = hierarchical_topics_mod(topic_model, docs)
        topics_vis = visualize_hierarchical_documents_custom(topic_model, docs, label_list, hierarchical_topics, reduced_embeddings=reduced_embeddings, sample = sample_prop, hide_document_hover= False, custom_labels=True, width= 1200, height = 750)
        #topics_vis = topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings, sample = sample_prop, hide_document_hover= False, custom_labels=True, width= 1200, height = 750)
        topics_vis_2 = topic_model.visualize_hierarchy(hierarchical_topics=hierarchical_topics, width= 1200, height = 750)

        topics_vis_name = data_file_name_no_ext + '_' + 'vis_hierarchy_topic_doc_' + today_rev + '.html'
        topics_vis.write_html(topics_vis_name)
        output_list.append(topics_vis_name)

        topics_vis_2_name = data_file_name_no_ext + '_' + 'vis_hierarchy_' + today_rev + '.html'
        topics_vis_2.write_html(topics_vis_2_name)
        output_list.append(topics_vis_2_name)

    all_toc = time.perf_counter()
    time_out = f"Creating visualisation took {all_toc - vis_tic:0.1f} seconds"
    print(time_out)

    return time_out, output_list, topics_vis, topics_vis_2

def save_as_pytorch_model(topic_model, data_file_name_no_ext , progress=gr.Progress()):

    if not topic_model:
        return "No Pytorch model found.", None

    progress(0, desc= "Saving topic model in Pytorch format")

    output_list = []


    topic_model_save_name_folder = "output_model/" + data_file_name_no_ext + "_topics_" + today_rev# + ".safetensors"
    topic_model_save_name_zip = topic_model_save_name_folder + ".zip"

    # Clear folder before replacing files
    delete_files_in_folder(topic_model_save_name_folder)

    topic_model.save(topic_model_save_name_folder, serialization='pytorch', save_embedding_model=True, save_ctfidf=False)

    # Zip file example
    
    zip_folder(topic_model_save_name_folder, topic_model_save_name_zip)
    output_list.append(topic_model_save_name_zip)

    return "Model saved in Pytorch format.", output_list

# Gradio app

block = gr.Blocks(theme = gr.themes.Base())

with block:

    data_state = gr.State(pd.DataFrame())
    embeddings_state = gr.State(np.array([]))
    topic_model_state = gr.State()
    docs_state = gr.State()
    data_file_name_no_ext_state = gr.State()
    label_list_state = gr.State(pd.DataFrame())
 
    gr.Markdown(
    """
    # Topic modeller
    Generate topics from open text in tabular data. Upload a file (csv, xlsx, or parquet), then specify the open text column that you want to use to generate topics, and another for labels in the visualisation. If you have an embeddings .npz file of the text made using the 'BAAI/bge-small-en-v1.5' model, you can load this in at the same time to skip the first modelling step. If you have a pre-defined list of topics, you can upload this as a csv file under 'I have my own list of topics...'. Further configuration options are available under the 'Options' tab.

    Suggested test dataset: https://huggingface.co/datasets/rag-datasets/mini_wikipedia/tree/main/data (passages.parquet)
    """)    
          
    with gr.Tab("Load files and find topics"):
        with gr.Accordion("Load data file", open = True):
            in_files = gr.File(label="Input text from file", file_count="multiple")
            with gr.Row():
                in_colnames = gr.Dropdown(choices=["Choose a column"], multiselect = True, label="Select column to find topics (first will be chosen if multiple selected).")                

        with gr.Accordion("I have my own list of topics (zero shot topic modelling).", open = False):
            candidate_topics = gr.File(label="Input topics from file (csv). File should have at least one column with a header and topic keywords in cells below. Topics will be taken from the first column of the file. Currently not compatible with low-resource embeddings.")
            zero_shot_similarity = gr.Slider(minimum = 0.5, maximum = 1, value = 0.65, step = 0.001, label = "Minimum similarity value for document to be assigned to zero-shot topic.")

        with gr.Row():
            min_docs_slider = gr.Slider(minimum = 2, maximum = 1000, value = 15, step = 1, label = "Minimum number of similar documents needed to make a topic.")
            max_topics_slider = gr.Slider(minimum = 2, maximum = 500, value = 10, step = 1, label = "Maximum number of topics")

        with gr.Row():
            topics_btn = gr.Button("Extract topics")
            
        with gr.Row():
            output_single_text = gr.Textbox(label="Output topics")
            output_file = gr.File(label="Output file")

        with gr.Accordion("Post processing options.", open = True):
            with gr.Row():
                reduce_outliers_btn = gr.Button("Reduce outliers")
                represent_llm_btn = gr.Button("Generate topic labels with LLMs")
                save_pytorch_btn = gr.Button("Save model in Pytorch format")

        #logs = gr.Textbox(label="Processing logs.")

    with gr.Tab("Visualise"):
        with gr.Row():
            in_label = gr.Dropdown(choices=["Choose a column"], multiselect = True, label="Select column for labelling documents in output visualisations.")
            visualisation_type_radio = gr.Radio(label="Visualisation type", choices=["Topic document graph", "Hierarchical view"])
        sample_slide = gr.Slider(minimum = 0.01, maximum = 1, value = 0.1, step = 0.01, label = "Proportion of data points to show on output visualisations.")
        plot_btn = gr.Button("Visualise topic model")
        with gr.Row():
            vis_output_single_text = gr.Textbox(label="Visualisation output text")
            out_plot_file = gr.File(label="Output plots to file", file_count="multiple")
        plot = gr.Plot(label="Visualise your topics here.")
        plot_2 = gr.Plot(label="Visualise your topics here.")

    
    with gr.Tab("Options"):
        with gr.Accordion("Data load and processing options", open = True):
            with gr.Row():
                anonymise_drop = gr.Dropdown(value = "No", choices=["Yes", "No"], multiselect=False, label="Anonymise data on file load. Names and other details are replaced with tags e.g. '<person>'.")
                embedding_super_compress = gr.Dropdown(label = "Round embeddings to three dp for smaller files with less accuracy.", value="No", choices=["Yes", "No"])
                seed_number = gr.Number(label="Random seed to use for dimensionality reduction.", minimum=0, step=1, value=42, precision=0)
                calc_probs = gr.Dropdown(label="Calculate all topic probabilities (i.e. a separate document prob. value for each topic)", value="No", choices=["Yes", "No"])
            with gr.Row():
                low_resource_mode_opt = gr.Dropdown(label = "Use low resource embeddings and processing.", value="No", choices=["Yes", "No"])
                return_intermediate_files = gr.Dropdown(label = "Return intermediate processing files from file preparation.", value="Yes", choices=["Yes", "No"])
                save_topic_model = gr.Dropdown(label = "Save topic model to file.", value="Yes", choices=["Yes", "No"])

    # Update column names dropdown when file uploaded
    in_files.upload(fn=initial_file_load, inputs=[in_files], outputs=[in_colnames, in_label, data_state, output_single_text, topic_model_state, embeddings_state, data_file_name_no_ext_state, label_list_state])    
    in_colnames.change(dummy_function, in_colnames, None)

    topics_btn.click(fn=extract_topics, inputs=[data_state, in_files, min_docs_slider, in_colnames, max_topics_slider, candidate_topics, data_file_name_no_ext_state, label_list_state, anonymise_drop, return_intermediate_files, embedding_super_compress, low_resource_mode_opt, save_topic_model, embeddings_state, zero_shot_similarity, seed_number, calc_probs], outputs=[output_single_text, output_file, embeddings_state, data_file_name_no_ext_state, topic_model_state, docs_state], api_name="topics")

    reduce_outliers_btn.click(fn=reduce_outliers, inputs=[topic_model_state, docs_state, embeddings_state, data_file_name_no_ext_state, save_topic_model], outputs=[output_single_text, output_file, topic_model_state], api_name="reduce_outliers")

    represent_llm_btn.click(fn=represent_topics, inputs=[topic_model_state, docs_state, embeddings_state, data_file_name_no_ext_state, low_resource_mode_opt, save_topic_model], outputs=[output_single_text, output_file, topic_model_state], api_name="represent_llm")

    save_pytorch_btn.click(fn=save_as_pytorch_model, inputs=[topic_model_state, data_file_name_no_ext_state], outputs=[output_single_text, output_file])

    plot_btn.click(fn=visualise_topics, inputs=[topic_model_state, data_state, data_file_name_no_ext_state, low_resource_mode_opt, embeddings_state, in_label, in_colnames, sample_slide, visualisation_type_radio, seed_number], outputs=[vis_output_single_text, out_plot_file, plot, plot_2], api_name="plot")

    #block.load(read_logs, None, logs, every=5)

block.queue().launch(debug=True)#, server_name="0.0.0.0", ssl_verify=False, server_port=7860)