T Le commited on
Commit
6d81f16
·
2 Parent(s): 00012be 6e13ca0

Merge from main brach

Browse files
Files changed (1) hide show
  1. pages/2 Topic Modeling.py +671 -671
pages/2 Topic Modeling.py CHANGED
@@ -1,671 +1,671 @@
1
- #import module
2
- import streamlit as st
3
- import streamlit.components.v1 as components
4
- import pandas as pd
5
- import numpy as np
6
- import re
7
- import string
8
- import nltk
9
- nltk.download('wordnet')
10
- from nltk.stem import WordNetLemmatizer
11
- nltk.download('stopwords')
12
- from nltk.corpus import stopwords
13
- import gensim
14
- import gensim.corpora as corpora
15
- from gensim.corpora import Dictionary
16
- from gensim.models.coherencemodel import CoherenceModel
17
- from gensim.models.ldamodel import LdaModel
18
- from gensim.models import Phrases
19
- from gensim.models.phrases import Phraser
20
- from pprint import pprint
21
- import pickle
22
- import pyLDAvis
23
- import pyLDAvis.gensim_models as gensimvis
24
- from io import StringIO
25
- from ipywidgets.embed import embed_minimal_html
26
- from nltk.stem.snowball import SnowballStemmer
27
- from bertopic import BERTopic
28
- from bertopic.representation import KeyBERTInspired, MaximalMarginalRelevance, OpenAI, TextGeneration
29
- import plotly.express as px
30
- from sklearn.cluster import KMeans
31
- from sklearn.feature_extraction.text import CountVectorizer
32
- import bitermplus as btm
33
- import tmplot as tmp
34
- import tomotopy
35
- import sys
36
- import spacy
37
- import en_core_web_sm
38
- import pipeline
39
- from html2image import Html2Image
40
- from umap import UMAP
41
- import os
42
- import time
43
- import json
44
- from tools import sourceformat as sf
45
- import datamapplot
46
- from sentence_transformers import SentenceTransformer
47
- import openai
48
- from transformers import pipeline
49
-
50
- #===config===
51
- st.set_page_config(
52
- page_title="Coconut",
53
- page_icon="🥥",
54
- layout="wide",
55
- initial_sidebar_state="collapsed"
56
- )
57
-
58
- hide_streamlit_style = """
59
- <style>
60
- #MainMenu
61
- {visibility: hidden;}
62
- footer {visibility: hidden;}
63
- [data-testid="collapsedControl"] {display: none}
64
- </style>
65
- """
66
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
67
-
68
- with st.popover("🔗 Menu"):
69
- st.page_link("https://www.coconut-libtool.com/", label="Home", icon="🏠")
70
- st.page_link("pages/1 Scattertext.py", label="Scattertext", icon="1️⃣")
71
- st.page_link("pages/2 Topic Modeling.py", label="Topic Modeling", icon="2️⃣")
72
- st.page_link("pages/3 Bidirected Network.py", label="Bidirected Network", icon="3️⃣")
73
- st.page_link("pages/4 Sunburst.py", label="Sunburst", icon="4️⃣")
74
- st.page_link("pages/5 Burst Detection.py", label="Burst Detection", icon="5️⃣")
75
- st.page_link("pages/6 Keywords Stem.py", label="Keywords Stem", icon="6️⃣")
76
- st.page_link("pages/7 Sentiment Analysis.py", label="Sentiment Analysis", icon="7️⃣")
77
- st.page_link("pages/8 Shifterator.py", label="Shifterator", icon="8️⃣")
78
- st.page_link("pages/9 Summarization.py", label = "Summarization",icon ="9️⃣")
79
- st.page_link("pages/10 WordCloud.py", label = "WordCloud", icon = "🔟")
80
-
81
- st.header("Topic Modeling", anchor=False)
82
- st.subheader('Put your file here...', anchor=False)
83
-
84
- #========unique id========
85
- @st.cache_resource(ttl=3600)
86
- def create_list():
87
- l = [1, 2, 3]
88
- return l
89
-
90
- l = create_list()
91
- first_list_value = l[0]
92
- l[0] = first_list_value + 1
93
- uID = str(l[0])
94
-
95
- @st.cache_data(ttl=3600)
96
- def get_ext(uploaded_file):
97
- extype = uID+uploaded_file.name
98
- return extype
99
-
100
- #===clear cache===
101
-
102
- def reset_biterm():
103
- try:
104
- biterm_map.clear()
105
- biterm_bar.clear()
106
- except NameError:
107
- biterm_topic.clear()
108
-
109
- def reset_all():
110
- st.cache_data.clear()
111
-
112
- #===avoiding deadlock===
113
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
114
-
115
- #===upload file===
116
- @st.cache_data(ttl=3600)
117
- def upload(file):
118
- papers = pd.read_csv(uploaded_file)
119
- if "About the data" in papers.columns[0]:
120
- papers = sf.dim(papers)
121
- col_dict = {'MeSH terms': 'Keywords',
122
- 'PubYear': 'Year',
123
- 'Times cited': 'Cited by',
124
- 'Publication Type': 'Document Type'
125
- }
126
- papers.rename(columns=col_dict, inplace=True)
127
-
128
- return papers
129
-
130
- @st.cache_data(ttl=3600)
131
- def conv_txt(extype):
132
- if("PMID" in (uploaded_file.read()).decode()):
133
- uploaded_file.seek(0)
134
- papers = sf.medline(uploaded_file)
135
- print(papers)
136
- return papers
137
- col_dict = {'TI': 'Title',
138
- 'SO': 'Source title',
139
- 'DE': 'Author Keywords',
140
- 'DT': 'Document Type',
141
- 'AB': 'Abstract',
142
- 'TC': 'Cited by',
143
- 'PY': 'Year',
144
- 'ID': 'Keywords Plus',
145
- 'rights_date_used': 'Year'}
146
- uploaded_file.seek(0)
147
- papers = pd.read_csv(uploaded_file, sep='\t')
148
- if("htid" in papers.columns):
149
- papers = sf.htrc(papers)
150
- papers.rename(columns=col_dict, inplace=True)
151
- print(papers)
152
- return papers
153
-
154
-
155
- @st.cache_data(ttl=3600)
156
- def conv_json(extype):
157
- col_dict={'title': 'title',
158
- 'rights_date_used': 'Year',
159
- }
160
-
161
- data = json.load(uploaded_file)
162
- hathifile = data['gathers']
163
- keywords = pd.DataFrame.from_records(hathifile)
164
-
165
- keywords = sf.htrc(keywords)
166
- keywords.rename(columns=col_dict,inplace=True)
167
- return keywords
168
-
169
- @st.cache_resource(ttl=3600)
170
- def conv_pub(extype):
171
- if (get_ext(extype)).endswith('.tar.gz'):
172
- bytedata = extype.read()
173
- keywords = sf.readPub(bytedata)
174
- elif (get_ext(extype)).endswith('.xml'):
175
- bytedata = extype.read()
176
- keywords = sf.readxml(bytedata)
177
- return keywords
178
-
179
- #===Read data===
180
- uploaded_file = st.file_uploader('', type=['csv', 'txt','json','tar.gz','xml'], on_change=reset_all)
181
-
182
- if uploaded_file is not None:
183
- try:
184
- extype = get_ext(uploaded_file)
185
-
186
- if extype.endswith('.csv'):
187
- papers = upload(extype)
188
- elif extype.endswith('.txt'):
189
- papers = conv_txt(extype)
190
-
191
- elif extype.endswith('.json'):
192
- papers = conv_json(extype)
193
- elif extype.endswith('.tar.gz') or extype.endswith('.xml'):
194
- papers = conv_pub(uploaded_file)
195
-
196
- coldf = sorted(papers.select_dtypes(include=['object']).columns.tolist())
197
-
198
- c1, c2, c3 = st.columns([3,3,4])
199
- method = c1.selectbox(
200
- 'Choose method',
201
- ('Choose...', 'pyLDA', 'Biterm', 'BERTopic'))
202
- ColCho = c2.selectbox('Choose column', (["Abstract","Title", "Abstract + Title"]))
203
- num_cho = c3.number_input('Choose number of topics', min_value=2, max_value=30, value=5)
204
-
205
- d1, d2 = st.columns([3,7])
206
- xgram = d1.selectbox("N-grams", ("1", "2", "3"))
207
- xgram = int(xgram)
208
- words_to_remove = d2.text_input("Remove specific words. Separate words by semicolons (;)")
209
-
210
- rem_copyright = d1.toggle('Remove copyright statement', value=True)
211
- rem_punc = d2.toggle('Remove punctuation', value=True)
212
-
213
- #===advance settings===
214
- with st.expander("🧮 Show advance settings"):
215
- t1, t2, t3 = st.columns([3,3,4])
216
- if method == 'pyLDA':
217
- py_random_state = t1.number_input('Random state', min_value=0, max_value=None, step=1)
218
- py_chunksize = t2.number_input('Chunk size', value=100 , min_value=10, max_value=None, step=1)
219
- opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
220
-
221
- elif method == 'Biterm':
222
- btm_seed = t1.number_input('Random state seed', value=100 , min_value=1, max_value=None, step=1)
223
- btm_iterations = t2.number_input('Iterations number', value=20 , min_value=2, max_value=None, step=1)
224
- opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
225
-
226
- elif method == 'BERTopic':
227
- u1, u2 = st.columns([5,5])
228
-
229
- bert_top_n_words = u1.number_input('top_n_words', value=5 , min_value=5, max_value=25, step=1)
230
- bert_random_state = u2.number_input('random_state', value=42 , min_value=1, max_value=None, step=1)
231
- bert_n_components = u1.number_input('n_components', value=5 , min_value=1, max_value=None, step=1)
232
- bert_n_neighbors = u2.number_input('n_neighbors', value=15 , min_value=1, max_value=None, step=1)
233
- bert_embedding_model = st.radio(
234
- "embedding_model",
235
- ["all-MiniLM-L6-v2", "paraphrase-multilingual-MiniLM-L12-v2", "en_core_web_sm"], index=0, horizontal=True)
236
-
237
- fine_tuning = st.toggle("Use Fine-tuning")
238
- if fine_tuning:
239
- topic_labelling = st.toggle("Automatic topic labelling")
240
- if topic_labelling:
241
- llm_provider = st.selectbox("Model",["OpenAI/gpt-4o","Google/flan-t5","LiquidAI/LFM2-350M"])
242
- if llm_provider == "OpenAI/gpt-4o":
243
- api_key = st.text_input("API Key")
244
-
245
- else:
246
- st.write('Please choose your preferred method')
247
-
248
- #===clean csv===
249
- @st.cache_data(ttl=3600, show_spinner=False)
250
- def clean_csv(extype):
251
- if (ColCho=="Abstract + Title"):
252
- papers["Abstract + Title"] = papers["Title"] + " " + papers["Abstract"]
253
- st.write(papers["Abstract + Title"])
254
-
255
- paper = papers.dropna(subset=[ColCho])
256
-
257
- #===mapping===
258
- paper['Abstract_pre'] = paper[ColCho].map(lambda x: x.lower())
259
- if rem_punc:
260
- paper['Abstract_pre'] = paper['Abstract_pre'].map(
261
- lambda x: re.sub(f"[{re.escape(string.punctuation)}]", " ", x)
262
- ).map(lambda x: re.sub(r"\s+", " ", x).strip())
263
- paper['Abstract_pre'] = paper['Abstract_pre'].str.replace('[\u2018\u2019\u201c\u201d]', '', regex=True)
264
- if rem_copyright:
265
- paper['Abstract_pre'] = paper['Abstract_pre'].map(lambda x: re.sub('©.*', '', x))
266
-
267
- #===stopword removal===
268
- stop = stopwords.words('english')
269
- paper['Abstract_stop'] = paper['Abstract_pre'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
270
-
271
- #===lemmatize===
272
- lemmatizer = WordNetLemmatizer()
273
-
274
- @st.cache_resource(ttl=3600)
275
- def lemmatize_words(text):
276
- words = text.split()
277
- words = [lemmatizer.lemmatize(word) for word in words]
278
- return ' '.join(words)
279
- paper['Abstract_lem'] = paper['Abstract_stop'].apply(lemmatize_words)
280
-
281
- words_rmv = [word.strip() for word in words_to_remove.split(";")]
282
- remove_dict = {word: None for word in words_rmv}
283
-
284
- @st.cache_resource(ttl=3600)
285
- def remove_words(text):
286
- words = text.split()
287
- cleaned_words = [word for word in words if word not in remove_dict]
288
- return ' '.join(cleaned_words)
289
- paper['Abstract_lem'] = paper['Abstract_lem'].map(remove_words)
290
-
291
- topic_abs = paper.Abstract_lem.values.tolist()
292
- return topic_abs, paper
293
-
294
- topic_abs, paper=clean_csv(extype)
295
-
296
- if st.button("Submit", on_click=reset_all):
297
- num_topic = num_cho
298
-
299
- if method == 'BERTopic':
300
- st.info('BERTopic is an expensive process when dealing with a large volume of text with our existing resources. Please kindly wait until the visualization appears.', icon="ℹ️")
301
-
302
- #===topic===
303
- if method == 'Choose...':
304
- st.write('')
305
-
306
- elif method == 'pyLDA':
307
- tab1, tab2, tab3, tab4 = st.tabs(["📈 Generate visualization", "📃 Reference", "📓 Recommended Reading", "⬇️ Download Help"])
308
-
309
- with tab1:
310
- #===visualization===
311
- @st.cache_data(ttl=3600, show_spinner=False)
312
- def pylda(extype):
313
- topic_abs_LDA = [t.split(' ') for t in topic_abs]
314
-
315
- bigram = Phrases(topic_abs_LDA, min_count=xgram, threshold=opt_threshold)
316
- trigram = Phrases(bigram[topic_abs_LDA], threshold=opt_threshold)
317
- bigram_mod = Phraser(bigram)
318
- trigram_mod = Phraser(trigram)
319
-
320
- topic_abs_LDA = [trigram_mod[bigram_mod[doc]] for doc in topic_abs_LDA]
321
-
322
- id2word = Dictionary(topic_abs_LDA)
323
- corpus = [id2word.doc2bow(text) for text in topic_abs_LDA]
324
- #===LDA===
325
- lda_model = LdaModel(corpus=corpus,
326
- id2word=id2word,
327
- num_topics=num_topic,
328
- random_state=py_random_state,
329
- chunksize=py_chunksize,
330
- alpha='auto',
331
- per_word_topics=False)
332
- pprint(lda_model.print_topics())
333
- doc_lda = lda_model[corpus]
334
- topics = lda_model.show_topics(num_words = 30,formatted=False)
335
-
336
- #===visualization===
337
- coherence_model_lda = CoherenceModel(model=lda_model, texts=topic_abs_LDA, dictionary=id2word, coherence='c_v')
338
- coherence_lda = coherence_model_lda.get_coherence()
339
- vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
340
- py_lda_vis_html = pyLDAvis.prepared_data_to_html(vis)
341
- return py_lda_vis_html, coherence_lda, vis, topics
342
-
343
- with st.spinner('Performing computations. Please wait ...'):
344
- try:
345
- py_lda_vis_html, coherence_lda, vis, topics = pylda(extype)
346
- st.write('Coherence score: ', coherence_lda)
347
- components.html(py_lda_vis_html, width=1500, height=800)
348
- st.markdown('Copyright (c) 2015, Ben Mabey. https://github.com/bmabey/pyLDAvis')
349
-
350
- @st.cache_data(ttl=3600, show_spinner=False)
351
- def img_lda(vis):
352
- pyLDAvis.save_html(vis, 'output.html')
353
- hti = Html2Image()
354
- hti.browser.flags = ['--default-background-color=ffffff', '--hide-scrollbars']
355
- hti.browser.use_new_headless = None
356
- css = "body {background: white;}"
357
- hti.screenshot(
358
- other_file='output.html', css_str=css, size=(1500, 800),
359
- save_as='ldavis_img.png'
360
- )
361
-
362
- img_lda(vis)
363
-
364
- d1, d2 = st.columns(2)
365
- with open("ldavis_img.png", "rb") as file:
366
- btn = d1.download_button(
367
- label="Download image",
368
- data=file,
369
- file_name="ldavis_img.png",
370
- mime="image/png"
371
- )
372
-
373
- #===download results===#
374
- resultf = pd.DataFrame(topics)
375
- #formatting
376
- resultf = resultf.transpose()
377
- resultf = resultf.drop([0])
378
- resultf = resultf.explode(list(range(len(resultf.columns))), ignore_index=False)
379
-
380
- resultcsv = resultf.to_csv().encode("utf-8")
381
- d2.download_button(
382
- label = "Download Results",
383
- data=resultcsv,
384
- file_name="results.csv",
385
- mime="text\csv",
386
- on_click="ignore")
387
-
388
- except NameError as f:
389
- st.warning('🖱️ Please click Submit')
390
-
391
- with tab2:
392
- st.markdown('**Sievert, C., & Shirley, K. (2014). LDAvis: A method for visualizing and interpreting topics. Proceedings of the Workshop on Interactive Language Learning, Visualization, and Interfaces.** https://doi.org/10.3115/v1/w14-3110')
393
-
394
- with tab3:
395
- st.markdown('**Chen, X., & Wang, H. (2019, January). Automated chat transcript analysis using topic modeling for library reference services. Proceedings of the Association for Information Science and Technology, 56(1), 368–371.** https://doi.org/10.1002/pra2.31')
396
- st.markdown('**Joo, S., Ingram, E., & Cahill, M. (2021, December 15). Exploring Topics and Genres in Storytime Books: A Text Mining Approach. Evidence Based Library and Information Practice, 16(4), 41–62.** https://doi.org/10.18438/eblip29963')
397
- st.markdown('**Lamba, M., & Madhusudhan, M. (2021, July 31). Topic Modeling. Text Mining for Information Professionals, 105–137.** https://doi.org/10.1007/978-3-030-85085-2_4')
398
- st.markdown('**Lamba, M., & Madhusudhan, M. (2019, June 7). Mapping of topics in DESIDOC Journal of Library and Information Technology, India: a study. Scientometrics, 120(2), 477–505.** https://doi.org/10.1007/s11192-019-03137-5')
399
-
400
- with tab4:
401
- st.subheader(':blue[pyLDA]', anchor=False)
402
- st.button('Download image')
403
- st.text("Click Download Image button.")
404
- st.divider()
405
- st.subheader(':blue[Downloading CSV Results]', anchor=False)
406
- st.button("Download Results")
407
- st.text("Click Download results button at bottom of page")
408
-
409
- #===Biterm===
410
- elif method == 'Biterm':
411
-
412
- #===optimize Biterm===
413
- @st.cache_data(ttl=3600, show_spinner=False)
414
- def biterm_topic(extype):
415
- tokenized_abs = [t.split(' ') for t in topic_abs]
416
-
417
- bigram = Phrases(tokenized_abs, min_count=xgram, threshold=opt_threshold)
418
- trigram = Phrases(bigram[tokenized_abs], threshold=opt_threshold)
419
- bigram_mod = Phraser(bigram)
420
- trigram_mod = Phraser(trigram)
421
-
422
- topic_abs_ngram = [trigram_mod[bigram_mod[doc]] for doc in tokenized_abs]
423
-
424
- topic_abs_str = [' '.join(doc) for doc in topic_abs_ngram]
425
-
426
-
427
- X, vocabulary, vocab_dict = btm.get_words_freqs(topic_abs_str)
428
- tf = np.array(X.sum(axis=0)).ravel()
429
- docs_vec = btm.get_vectorized_docs(topic_abs, vocabulary)
430
- docs_lens = list(map(len, docs_vec))
431
- biterms = btm.get_biterms(docs_vec)
432
-
433
- model = btm.BTM(X, vocabulary, seed=btm_seed, T=num_topic, M=20, alpha=50/8, beta=0.01)
434
- model.fit(biterms, iterations=btm_iterations)
435
-
436
- p_zd = model.transform(docs_vec)
437
- coherence = model.coherence_
438
- phi = tmp.get_phi(model)
439
- topics_coords = tmp.prepare_coords(model)
440
- totaltop = topics_coords.label.values.tolist()
441
- perplexity = model.perplexity_
442
- top_topics = model.df_words_topics_
443
-
444
- return topics_coords, phi, totaltop, perplexity, top_topics
445
-
446
- tab1, tab2, tab3, tab4 = st.tabs(["📈 Generate visualization", "📃 Reference", "📓 Recommended Reading", "⬇️ Download Help"])
447
- with tab1:
448
- try:
449
- with st.spinner('Performing computations. Please wait ...'):
450
- topics_coords, phi, totaltop, perplexity, top_topics = biterm_topic(extype)
451
- col1, col2 = st.columns([4,6])
452
-
453
- @st.cache_data(ttl=3600)
454
- def biterm_map(extype):
455
- btmvis_coords = tmp.plot_scatter_topics(topics_coords, size_col='size', label_col='label', topic=numvis)
456
- return btmvis_coords
457
-
458
- @st.cache_data(ttl=3600)
459
- def biterm_bar(extype):
460
- terms_probs = tmp.calc_terms_probs_ratio(phi, topic=numvis, lambda_=1)
461
- btmvis_probs = tmp.plot_terms(terms_probs, font_size=12)
462
- return btmvis_probs
463
-
464
- with col1:
465
- st.write('Perplexity score: ', perplexity)
466
- st.write('')
467
- numvis = st.selectbox(
468
- 'Choose topic',
469
- (totaltop), on_change=reset_biterm)
470
- btmvis_coords = biterm_map(extype)
471
- st.altair_chart(btmvis_coords)
472
- with col2:
473
- btmvis_probs = biterm_bar(extype)
474
- st.altair_chart(btmvis_probs, use_container_width=True)
475
-
476
- #===download results===#
477
- resultcsv = top_topics.to_csv().encode("utf-8")
478
- st.download_button(label = "Download Results", data=resultcsv, file_name="results.csv", mime="text\csv", on_click="ignore")
479
-
480
- except ValueError as g:
481
- st.error('🙇‍♂️ Please raise the number of topics and click submit')
482
-
483
- except NameError as f:
484
- st.warning('🖱️ Please click Submit')
485
-
486
- with tab2:
487
- st.markdown('**Yan, X., Guo, J., Lan, Y., & Cheng, X. (2013, May 13). A biterm topic model for short texts. Proceedings of the 22nd International Conference on World Wide Web.** https://doi.org/10.1145/2488388.2488514')
488
- with tab3:
489
- st.markdown('**Cai, M., Shah, N., Li, J., Chen, W. H., Cuomo, R. E., Obradovich, N., & Mackey, T. K. (2020, August 26). Identification and characterization of tweets related to the 2015 Indiana HIV outbreak: A retrospective infoveillance study. PLOS ONE, 15(8), e0235150.** https://doi.org/10.1371/journal.pone.0235150')
490
- st.markdown('**Chen, Y., Dong, T., Ban, Q., & Li, Y. (2021). What Concerns Consumers about Hypertension? A Comparison between the Online Health Community and the Q&A Forum. International Journal of Computational Intelligence Systems, 14(1), 734.** https://doi.org/10.2991/ijcis.d.210203.002')
491
- st.markdown('**George, Crissandra J., "AMBIGUOUS APPALACHIANNESS: A LINGUISTIC AND PERCEPTUAL INVESTIGATION INTO ARC-LABELED PENNSYLVANIA COUNTIES" (2022). Theses and Dissertations-- Linguistics. 48.** https://doi.org/10.13023/etd.2022.217')
492
- st.markdown('**Li, J., Chen, W. H., Xu, Q., Shah, N., Kohler, J. C., & Mackey, T. K. (2020). Detection of self-reported experiences with corruption on twitter using unsupervised machine learning. Social Sciences & Humanities Open, 2(1), 100060.** https://doi.org/10.1016/j.ssaho.2020.100060')
493
- with tab4:
494
- st.subheader(':blue[Biterm]', anchor=False)
495
- st.text("Click the three dots at the top right then select the desired format.")
496
- st.markdown("![Downloading visualization](https://raw.githubusercontent.com/faizhalas/library-tools/main/images/download_biterm.jpg)")
497
- st.divider()
498
- st.subheader(':blue[Downloading CSV Results]', anchor=False)
499
- st.button("Download Results")
500
- st.text("Click Download results button at bottom of page")
501
-
502
-
503
- #===BERTopic===
504
- elif method == 'BERTopic':
505
- @st.cache_resource(ttl = 3600, show_spinner=False)
506
- #@st.cache_data(ttl=3600, show_spinner=False)
507
- def bertopic_vis(extype):
508
- umap_model = UMAP(n_neighbors=bert_n_neighbors, n_components=bert_n_components,
509
- min_dist=0.0, metric='cosine', random_state=bert_random_state)
510
- cluster_model = KMeans(n_clusters=num_topic)
511
- if bert_embedding_model == 'all-MiniLM-L6-v2':
512
- model = SentenceTransformer('all-MiniLM-L6-v2')
513
- lang = 'en'
514
- embeddings = model.encode(topic_abs, show_progress_bar=True)
515
-
516
- elif bert_embedding_model == 'en_core_web_sm':
517
- nlp = en_core_web_sm.load(exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
518
- model = nlp
519
- lang = 'en'
520
- embeddings = np.array([nlp(text).vector for text in topic_abs])
521
-
522
- elif bert_embedding_model == 'paraphrase-multilingual-MiniLM-L12-v2':
523
- model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
524
- lang = 'multilingual'
525
- embeddings = model.encode(topic_abs, show_progress_bar=True)
526
-
527
- representation_model = ""
528
-
529
- if fine_tuning:
530
- keybert = KeyBERTInspired()
531
- mmr = MaximalMarginalRelevance(diversity=0.3)
532
- representation_model = {
533
- "KeyBERT": keybert,
534
- "MMR": mmr,
535
- }
536
- if topic_labelling:
537
- if llm_provider == "OpenAI/gpt-4o":
538
- client = openai.OpenAI(api_key=api_key)
539
- representation_model = {
540
- "KeyBERT": keybert,
541
- "MMR": mmr,
542
- "test": OpenAI(client, model = "gpt-4o-mini", delay_in_seconds=10)
543
- }
544
- elif llm_provider == "Google/flan-t5":
545
- pipe = pipeline("text2text-generation", model = "google/flan-t5-base")
546
- clientmod = TextGeneration(pipe)
547
- representation_model = {
548
- "KeyBERT": keybert,
549
- "MMR": mmr,
550
- "test": clientmod
551
- }
552
- elif llm_provider == "LiquidAI/LFM2-350M":
553
- pipe = pipeline("text-generation", model = "LiquidAI/LFM2-350M")
554
- clientmod = TextGeneration(pipe)
555
- representation_model = {
556
- "KeyBERT": keybert,
557
- "MMR": mmr,
558
- "test": clientmod
559
- }
560
-
561
- vectorizer_model = CountVectorizer(ngram_range=(1, xgram), stop_words='english')
562
- topic_model = BERTopic(representation_model = representation_model, embedding_model=model, hdbscan_model=cluster_model, language=lang, umap_model=umap_model, vectorizer_model=vectorizer_model, top_n_words=bert_top_n_words)
563
- topics, probs = topic_model.fit_transform(topic_abs, embeddings=embeddings)
564
-
565
- if(fine_tuning and topic_labelling):
566
- generated_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["test"].values()]
567
- topic_model.set_topic_labels(generated_labels)
568
-
569
- return topic_model, topics, probs, embeddings
570
-
571
- @st.cache_resource(ttl = 3600, show_spinner=False)
572
- def Vis_Topics(extype):
573
- fig1 = topic_model.visualize_topics(custom_labels = True)
574
- return fig1
575
- @st.cache_resource(ttl = 3600, show_spinner=False)
576
- def Vis_Documents(extype):
577
- fig2 = topic_model.visualize_document_datamap(topic_abs, embeddings=embeddings, custom_labels = True)
578
- return fig2
579
- @st.cache_resource(ttl = 3600, show_spinner=False)
580
- def Vis_Hierarchy(extype):
581
- fig3 = topic_model.visualize_hierarchy(top_n_topics=num_topic, custom_labels = True)
582
- return fig3
583
- @st.cache_resource(ttl = 3600, show_spinner=False)
584
- def Vis_Heatmap(extype):
585
- global topic_model
586
- fig4 = topic_model.visualize_heatmap(n_clusters=num_topic-1, width=1000, height=1000, custom_labels = True)
587
- return fig4
588
- @st.cache_resource(ttl = 3600, show_spinner=False)
589
- def Vis_Barchart(extype):
590
- fig5 = topic_model.visualize_barchart(top_n_topics=num_topic, custom_labels = True)
591
- return fig5
592
-
593
- tab1, tab2, tab3, tab4 = st.tabs(["📈 Generate visualization", "📃 Reference", "📓 Recommended Reading", "⬇️ Download Help"])
594
- with tab1:
595
- try:
596
- with st.spinner('Performing computations. Please wait ...'):
597
-
598
- topic_model, topics, probs, embeddings = bertopic_vis(extype)
599
- time.sleep(.5)
600
- st.toast('Visualize Topics', icon='🏃')
601
- fig1 = Vis_Topics(extype)
602
-
603
- time.sleep(.5)
604
- st.toast('Visualize Document', icon='🏃')
605
- fig2 = Vis_Documents(extype)
606
-
607
- time.sleep(.5)
608
- st.toast('Visualize Document Hierarchy', icon='🏃')
609
- fig3 = Vis_Hierarchy(extype)
610
-
611
- time.sleep(.5)
612
- st.toast('Visualize Topic Similarity', icon='🏃')
613
- fig4 = Vis_Heatmap(extype)
614
-
615
- time.sleep(.5)
616
- st.toast('Visualize Terms', icon='🏃')
617
- fig5 = Vis_Barchart(extype)
618
-
619
- bertab1, bertab2, bertab3, bertab4, bertab5 = st.tabs(["Visualize Topics", "Visualize Terms", "Visualize Documents",
620
- "Visualize Document Hierarchy", "Visualize Topic Similarity"])
621
-
622
- with bertab1:
623
- st.plotly_chart(fig1, use_container_width=True)
624
- with bertab2:
625
- st.plotly_chart(fig5, use_container_width=True)
626
- with bertab3:
627
- st.plotly_chart(fig2, use_container_width=True)
628
- with bertab4:
629
- st.plotly_chart(fig3, use_container_width=True)
630
- with bertab5:
631
- st.plotly_chart(fig4, use_container_width=True)
632
-
633
- #===download results===#
634
- results = topic_model.get_topic_info()
635
- resultf = pd.DataFrame(results)
636
- resultcsv = resultf.to_csv().encode("utf-8")
637
- st.download_button(
638
- label = "Download Results",
639
- data=resultcsv,
640
- file_name="results.csv",
641
- mime="text\csv",
642
- on_click="ignore",
643
- )
644
-
645
- except ValueError:
646
- st.error('🙇‍♂️ Please raise the number of topics and click submit')
647
-
648
-
649
- except NameError:
650
- st.warning('🖱️ Please click Submit')
651
-
652
- with tab2:
653
- st.markdown('**Grootendorst, M. (2022). BERTopic: Neural topic modeling with a class-based TF-IDF procedure. arXiv preprint arXiv:2203.05794.** https://doi.org/10.48550/arXiv.2203.05794')
654
-
655
- with tab3:
656
- st.markdown('**Jeet Rawat, A., Ghildiyal, S., & Dixit, A. K. (2022, December 1). Topic modelling of legal documents using NLP and bidirectional encoder representations from transformers. Indonesian Journal of Electrical Engineering and Computer Science, 28(3), 1749.** https://doi.org/10.11591/ijeecs.v28.i3.pp1749-1755')
657
- st.markdown('**Yao, L. F., Ferawati, K., Liew, K., Wakamiya, S., & Aramaki, E. (2023, April 20). Disruptions in the Cystic Fibrosis Community’s Experiences and Concerns During the COVID-19 Pandemic: Topic Modeling and Time Series Analysis of Reddit Comments. Journal of Medical Internet Research, 25, e45249.** https://doi.org/10.2196/45249')
658
-
659
- with tab4:
660
- st.divider()
661
- st.subheader(':blue[BERTopic]', anchor=False)
662
- st.text("Click the camera icon on the top right menu")
663
- st.markdown("![Downloading visualization](https://raw.githubusercontent.com/faizhalas/library-tools/main/images/download_bertopic.jpg)")
664
- st.divider()
665
- st.subheader(':blue[Downloading CSV Results]', anchor=False)
666
- st.button("Download Results")
667
- st.text("Click Download results button at bottom of page")
668
-
669
- except:
670
- st.error("Please ensure that your file is correct. Please contact us if you find that this is an error.", icon="🚨")
671
- st.stop()
 
1
+ #import module
2
+ import streamlit as st
3
+ import streamlit.components.v1 as components
4
+ import pandas as pd
5
+ import numpy as np
6
+ import re
7
+ import string
8
+ import nltk
9
+ nltk.download('wordnet')
10
+ from nltk.stem import WordNetLemmatizer
11
+ nltk.download('stopwords')
12
+ from nltk.corpus import stopwords
13
+ import gensim
14
+ import gensim.corpora as corpora
15
+ from gensim.corpora import Dictionary
16
+ from gensim.models.coherencemodel import CoherenceModel
17
+ from gensim.models.ldamodel import LdaModel
18
+ from gensim.models import Phrases
19
+ from gensim.models.phrases import Phraser
20
+ from pprint import pprint
21
+ import pickle
22
+ import pyLDAvis
23
+ import pyLDAvis.gensim_models as gensimvis
24
+ from io import StringIO
25
+ from ipywidgets.embed import embed_minimal_html
26
+ from nltk.stem.snowball import SnowballStemmer
27
+ from bertopic import BERTopic
28
+ from bertopic.representation import KeyBERTInspired, MaximalMarginalRelevance, OpenAI, TextGeneration
29
+ import plotly.express as px
30
+ from sklearn.cluster import KMeans
31
+ from sklearn.feature_extraction.text import CountVectorizer
32
+ import bitermplus as btm
33
+ import tmplot as tmp
34
+ import tomotopy
35
+ import sys
36
+ import spacy
37
+ import en_core_web_sm
38
+ import pipeline
39
+ from html2image import Html2Image
40
+ from umap import UMAP
41
+ import os
42
+ import time
43
+ import json
44
+ from tools import sourceformat as sf
45
+ import datamapplot
46
+ from sentence_transformers import SentenceTransformer
47
+ import openai
48
+ from transformers import pipeline
49
+
50
+ #===config===
51
+ st.set_page_config(
52
+ page_title="Coconut",
53
+ page_icon="🥥",
54
+ layout="wide",
55
+ initial_sidebar_state="collapsed"
56
+ )
57
+
58
+ hide_streamlit_style = """
59
+ <style>
60
+ #MainMenu
61
+ {visibility: hidden;}
62
+ footer {visibility: hidden;}
63
+ [data-testid="collapsedControl"] {display: none}
64
+ </style>
65
+ """
66
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
67
+
68
+ with st.popover("🔗 Menu"):
69
+ st.page_link("https://www.coconut-libtool.com/", label="Home", icon="🏠")
70
+ st.page_link("pages/1 Scattertext.py", label="Scattertext", icon="1️⃣")
71
+ st.page_link("pages/2 Topic Modeling.py", label="Topic Modeling", icon="2️⃣")
72
+ st.page_link("pages/3 Bidirected Network.py", label="Bidirected Network", icon="3️⃣")
73
+ st.page_link("pages/4 Sunburst.py", label="Sunburst", icon="4️⃣")
74
+ st.page_link("pages/5 Burst Detection.py", label="Burst Detection", icon="5️⃣")
75
+ st.page_link("pages/6 Keywords Stem.py", label="Keywords Stem", icon="6️⃣")
76
+ st.page_link("pages/7 Sentiment Analysis.py", label="Sentiment Analysis", icon="7️⃣")
77
+ st.page_link("pages/8 Shifterator.py", label="Shifterator", icon="8️⃣")
78
+ st.page_link("pages/9 Summarization.py", label = "Summarization",icon ="9️⃣")
79
+ st.page_link("pages/10 WordCloud.py", label = "WordCloud", icon = "🔟")
80
+
81
+ st.header("Topic Modeling", anchor=False)
82
+ st.subheader('Put your file here...', anchor=False)
83
+
84
+ #========unique id========
85
+ @st.cache_resource(ttl=3600)
86
+ def create_list():
87
+ l = [1, 2, 3]
88
+ return l
89
+
90
+ l = create_list()
91
+ first_list_value = l[0]
92
+ l[0] = first_list_value + 1
93
+ uID = str(l[0])
94
+
95
+ @st.cache_data(ttl=3600)
96
+ def get_ext(uploaded_file):
97
+ extype = uID+uploaded_file.name
98
+ return extype
99
+
100
+ #===clear cache===
101
+
102
+ def reset_biterm():
103
+ try:
104
+ biterm_map.clear()
105
+ biterm_bar.clear()
106
+ except NameError:
107
+ biterm_topic.clear()
108
+
109
+ def reset_all():
110
+ st.cache_data.clear()
111
+
112
+ #===avoiding deadlock===
113
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
114
+
115
+ #===upload file===
116
+ @st.cache_data(ttl=3600)
117
+ def upload(file):
118
+ papers = pd.read_csv(uploaded_file)
119
+ if "About the data" in papers.columns[0]:
120
+ papers = sf.dim(papers)
121
+ col_dict = {'MeSH terms': 'Keywords',
122
+ 'PubYear': 'Year',
123
+ 'Times cited': 'Cited by',
124
+ 'Publication Type': 'Document Type'
125
+ }
126
+ papers.rename(columns=col_dict, inplace=True)
127
+
128
+ return papers
129
+
130
+ @st.cache_data(ttl=3600)
131
+ def conv_txt(extype):
132
+ if("PMID" in (uploaded_file.read()).decode()):
133
+ uploaded_file.seek(0)
134
+ papers = sf.medline(uploaded_file)
135
+ print(papers)
136
+ return papers
137
+ col_dict = {'TI': 'Title',
138
+ 'SO': 'Source title',
139
+ 'DE': 'Author Keywords',
140
+ 'DT': 'Document Type',
141
+ 'AB': 'Abstract',
142
+ 'TC': 'Cited by',
143
+ 'PY': 'Year',
144
+ 'ID': 'Keywords Plus',
145
+ 'rights_date_used': 'Year'}
146
+ uploaded_file.seek(0)
147
+ papers = pd.read_csv(uploaded_file, sep='\t')
148
+ if("htid" in papers.columns):
149
+ papers = sf.htrc(papers)
150
+ papers.rename(columns=col_dict, inplace=True)
151
+ print(papers)
152
+ return papers
153
+
154
+
155
+ @st.cache_data(ttl=3600)
156
+ def conv_json(extype):
157
+ col_dict={'title': 'title',
158
+ 'rights_date_used': 'Year',
159
+ }
160
+
161
+ data = json.load(uploaded_file)
162
+ hathifile = data['gathers']
163
+ keywords = pd.DataFrame.from_records(hathifile)
164
+
165
+ keywords = sf.htrc(keywords)
166
+ keywords.rename(columns=col_dict,inplace=True)
167
+ return keywords
168
+
169
+ @st.cache_resource(ttl=3600)
170
+ def conv_pub(extype):
171
+ if (get_ext(extype)).endswith('.tar.gz'):
172
+ bytedata = extype.read()
173
+ keywords = sf.readPub(bytedata)
174
+ elif (get_ext(extype)).endswith('.xml'):
175
+ bytedata = extype.read()
176
+ keywords = sf.readxml(bytedata)
177
+ return keywords
178
+
179
+ #===Read data===
180
+ uploaded_file = st.file_uploader('', type=['csv', 'txt','json','tar.gz','xml'], on_change=reset_all)
181
+
182
+ if uploaded_file is not None:
183
+ try:
184
+ extype = get_ext(uploaded_file)
185
+
186
+ if extype.endswith('.csv'):
187
+ papers = upload(extype)
188
+ elif extype.endswith('.txt'):
189
+ papers = conv_txt(extype)
190
+
191
+ elif extype.endswith('.json'):
192
+ papers = conv_json(extype)
193
+ elif extype.endswith('.tar.gz') or extype.endswith('.xml'):
194
+ papers = conv_pub(uploaded_file)
195
+
196
+ coldf = sorted(papers.select_dtypes(include=['object']).columns.tolist())
197
+
198
+ c1, c2, c3 = st.columns([3,3,4])
199
+ method = c1.selectbox(
200
+ 'Choose method',
201
+ ('Choose...', 'pyLDA', 'Biterm', 'BERTopic'))
202
+ ColCho = c2.selectbox('Choose column', (["Abstract","Title", "Abstract + Title"]))
203
+ num_cho = c3.number_input('Choose number of topics', min_value=2, max_value=30, value=5)
204
+
205
+ d1, d2 = st.columns([3,7])
206
+ xgram = d1.selectbox("N-grams", ("1", "2", "3"))
207
+ xgram = int(xgram)
208
+ words_to_remove = d2.text_input("Remove specific words. Separate words by semicolons (;)")
209
+
210
+ rem_copyright = d1.toggle('Remove copyright statement', value=True)
211
+ rem_punc = d2.toggle('Remove punctuation', value=True)
212
+
213
+ #===advance settings===
214
+ with st.expander("🧮 Show advance settings"):
215
+ t1, t2, t3 = st.columns([3,3,4])
216
+ if method == 'pyLDA':
217
+ py_random_state = t1.number_input('Random state', min_value=0, max_value=None, step=1)
218
+ py_chunksize = t2.number_input('Chunk size', value=100 , min_value=10, max_value=None, step=1)
219
+ opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
220
+
221
+ elif method == 'Biterm':
222
+ btm_seed = t1.number_input('Random state seed', value=100 , min_value=1, max_value=None, step=1)
223
+ btm_iterations = t2.number_input('Iterations number', value=20 , min_value=2, max_value=None, step=1)
224
+ opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
225
+
226
+ elif method == 'BERTopic':
227
+ u1, u2 = st.columns([5,5])
228
+
229
+ bert_top_n_words = u1.number_input('top_n_words', value=5 , min_value=5, max_value=25, step=1)
230
+ bert_random_state = u2.number_input('random_state', value=42 , min_value=1, max_value=None, step=1)
231
+ bert_n_components = u1.number_input('n_components', value=5 , min_value=1, max_value=None, step=1)
232
+ bert_n_neighbors = u2.number_input('n_neighbors', value=15 , min_value=1, max_value=None, step=1)
233
+ bert_embedding_model = st.radio(
234
+ "embedding_model",
235
+ ["all-MiniLM-L6-v2", "paraphrase-multilingual-MiniLM-L12-v2", "en_core_web_sm"], index=0, horizontal=True)
236
+
237
+ fine_tuning = st.toggle("Use Fine-tuning")
238
+ if fine_tuning:
239
+ topic_labelling = st.toggle("Automatic topic labelling")
240
+ if topic_labelling:
241
+ llm_provider = st.selectbox("Model",["OpenAI/gpt-4o","Google/flan-t5","LiquidAI/LFM2-350M"])
242
+ if llm_provider == "OpenAI/gpt-4o":
243
+ api_key = st.text_input("API Key")
244
+
245
+ else:
246
+ st.write('Please choose your preferred method')
247
+
248
+ #===clean csv===
249
+ @st.cache_data(ttl=3600, show_spinner=False)
250
+ def clean_csv(extype):
251
+ if (ColCho=="Abstract + Title"):
252
+ papers["Abstract + Title"] = papers["Title"] + " " + papers["Abstract"]
253
+ st.write(papers["Abstract + Title"])
254
+
255
+ paper = papers.dropna(subset=[ColCho])
256
+
257
+ #===mapping===
258
+ paper['Abstract_pre'] = paper[ColCho].map(lambda x: x.lower())
259
+ if rem_punc:
260
+ paper['Abstract_pre'] = paper['Abstract_pre'].map(
261
+ lambda x: re.sub(f"[{re.escape(string.punctuation)}]", " ", x)
262
+ ).map(lambda x: re.sub(r"\s+", " ", x).strip())
263
+ paper['Abstract_pre'] = paper['Abstract_pre'].str.replace('[\u2018\u2019\u201c\u201d]', '', regex=True)
264
+ if rem_copyright:
265
+ paper['Abstract_pre'] = paper['Abstract_pre'].map(lambda x: re.sub('©.*', '', x))
266
+
267
+ #===stopword removal===
268
+ stop = stopwords.words('english')
269
+ paper['Abstract_stop'] = paper['Abstract_pre'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
270
+
271
+ #===lemmatize===
272
+ lemmatizer = WordNetLemmatizer()
273
+
274
+ @st.cache_resource(ttl=3600)
275
+ def lemmatize_words(text):
276
+ words = text.split()
277
+ words = [lemmatizer.lemmatize(word) for word in words]
278
+ return ' '.join(words)
279
+ paper['Abstract_lem'] = paper['Abstract_stop'].apply(lemmatize_words)
280
+
281
+ words_rmv = [word.strip() for word in words_to_remove.split(";")]
282
+ remove_dict = {word: None for word in words_rmv}
283
+
284
+ @st.cache_resource(ttl=3600)
285
+ def remove_words(text):
286
+ words = text.split()
287
+ cleaned_words = [word for word in words if word not in remove_dict]
288
+ return ' '.join(cleaned_words)
289
+ paper['Abstract_lem'] = paper['Abstract_lem'].map(remove_words)
290
+
291
+ topic_abs = paper.Abstract_lem.values.tolist()
292
+ return topic_abs, paper
293
+
294
+ topic_abs, paper=clean_csv(extype)
295
+
296
+ if st.button("Submit", on_click=reset_all):
297
+ num_topic = num_cho
298
+
299
+ if method == 'BERTopic':
300
+ st.info('BERTopic is an expensive process when dealing with a large volume of text with our existing resources. Please kindly wait until the visualization appears.', icon="ℹ️")
301
+
302
+ #===topic===
303
+ if method == 'Choose...':
304
+ st.write('')
305
+
306
+ elif method == 'pyLDA':
307
+ tab1, tab2, tab3, tab4 = st.tabs(["📈 Generate visualization", "📃 Reference", "📓 Recommended Reading", "⬇️ Download Help"])
308
+
309
+ with tab1:
310
+ #===visualization===
311
+ @st.cache_data(ttl=3600, show_spinner=False)
312
+ def pylda(extype):
313
+ topic_abs_LDA = [t.split(' ') for t in topic_abs]
314
+
315
+ bigram = Phrases(topic_abs_LDA, min_count=xgram, threshold=opt_threshold)
316
+ trigram = Phrases(bigram[topic_abs_LDA], threshold=opt_threshold)
317
+ bigram_mod = Phraser(bigram)
318
+ trigram_mod = Phraser(trigram)
319
+
320
+ topic_abs_LDA = [trigram_mod[bigram_mod[doc]] for doc in topic_abs_LDA]
321
+
322
+ id2word = Dictionary(topic_abs_LDA)
323
+ corpus = [id2word.doc2bow(text) for text in topic_abs_LDA]
324
+ #===LDA===
325
+ lda_model = LdaModel(corpus=corpus,
326
+ id2word=id2word,
327
+ num_topics=num_topic,
328
+ random_state=py_random_state,
329
+ chunksize=py_chunksize,
330
+ alpha='auto',
331
+ per_word_topics=False)
332
+ pprint(lda_model.print_topics())
333
+ doc_lda = lda_model[corpus]
334
+ topics = lda_model.show_topics(num_words = 30,formatted=False)
335
+
336
+ #===visualization===
337
+ coherence_model_lda = CoherenceModel(model=lda_model, texts=topic_abs_LDA, dictionary=id2word, coherence='c_v')
338
+ coherence_lda = coherence_model_lda.get_coherence()
339
+ vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
340
+ py_lda_vis_html = pyLDAvis.prepared_data_to_html(vis)
341
+ return py_lda_vis_html, coherence_lda, vis, topics
342
+
343
+ with st.spinner('Performing computations. Please wait ...'):
344
+ try:
345
+ py_lda_vis_html, coherence_lda, vis, topics = pylda(extype)
346
+ st.write('Coherence score: ', coherence_lda)
347
+ components.html(py_lda_vis_html, width=1500, height=800)
348
+ st.markdown('Copyright (c) 2015, Ben Mabey. https://github.com/bmabey/pyLDAvis')
349
+
350
+ @st.cache_data(ttl=3600, show_spinner=False)
351
+ def img_lda(vis):
352
+ pyLDAvis.save_html(vis, 'output.html')
353
+ hti = Html2Image()
354
+ hti.browser.flags = ['--default-background-color=ffffff', '--hide-scrollbars']
355
+ hti.browser.use_new_headless = None
356
+ css = "body {background: white;}"
357
+ hti.screenshot(
358
+ other_file='output.html', css_str=css, size=(1500, 800),
359
+ save_as='ldavis_img.png'
360
+ )
361
+
362
+ img_lda(vis)
363
+
364
+ d1, d2 = st.columns(2)
365
+ with open("ldavis_img.png", "rb") as file:
366
+ btn = d1.download_button(
367
+ label="Download image",
368
+ data=file,
369
+ file_name="ldavis_img.png",
370
+ mime="image/png"
371
+ )
372
+
373
+ #===download results===#
374
+ resultf = pd.DataFrame(topics)
375
+ #formatting
376
+ resultf = resultf.transpose()
377
+ resultf = resultf.drop([0])
378
+ resultf = resultf.explode(list(range(len(resultf.columns))), ignore_index=False)
379
+
380
+ resultcsv = resultf.to_csv().encode("utf-8")
381
+ d2.download_button(
382
+ label = "Download Results",
383
+ data=resultcsv,
384
+ file_name="results.csv",
385
+ mime="text\csv",
386
+ on_click="ignore")
387
+
388
+ except NameError as f:
389
+ st.warning('🖱️ Please click Submit')
390
+
391
+ with tab2:
392
+ st.markdown('**Sievert, C., & Shirley, K. (2014). LDAvis: A method for visualizing and interpreting topics. Proceedings of the Workshop on Interactive Language Learning, Visualization, and Interfaces.** https://doi.org/10.3115/v1/w14-3110')
393
+
394
+ with tab3:
395
+ st.markdown('**Chen, X., & Wang, H. (2019, January). Automated chat transcript analysis using topic modeling for library reference services. Proceedings of the Association for Information Science and Technology, 56(1), 368–371.** https://doi.org/10.1002/pra2.31')
396
+ st.markdown('**Joo, S., Ingram, E., & Cahill, M. (2021, December 15). Exploring Topics and Genres in Storytime Books: A Text Mining Approach. Evidence Based Library and Information Practice, 16(4), 41–62.** https://doi.org/10.18438/eblip29963')
397
+ st.markdown('**Lamba, M., & Madhusudhan, M. (2021, July 31). Topic Modeling. Text Mining for Information Professionals, 105–137.** https://doi.org/10.1007/978-3-030-85085-2_4')
398
+ st.markdown('**Lamba, M., & Madhusudhan, M. (2019, June 7). Mapping of topics in DESIDOC Journal of Library and Information Technology, India: a study. Scientometrics, 120(2), 477–505.** https://doi.org/10.1007/s11192-019-03137-5')
399
+
400
+ with tab4:
401
+ st.subheader(':blue[pyLDA]', anchor=False)
402
+ st.button('Download image')
403
+ st.text("Click Download Image button.")
404
+ st.divider()
405
+ st.subheader(':blue[Downloading CSV Results]', anchor=False)
406
+ st.button("Download Results")
407
+ st.text("Click Download results button at bottom of page")
408
+
409
+ #===Biterm===
410
+ elif method == 'Biterm':
411
+
412
+ #===optimize Biterm===
413
+ @st.cache_data(ttl=3600, show_spinner=False)
414
+ def biterm_topic(extype):
415
+ tokenized_abs = [t.split(' ') for t in topic_abs]
416
+
417
+ bigram = Phrases(tokenized_abs, min_count=xgram, threshold=opt_threshold)
418
+ trigram = Phrases(bigram[tokenized_abs], threshold=opt_threshold)
419
+ bigram_mod = Phraser(bigram)
420
+ trigram_mod = Phraser(trigram)
421
+
422
+ topic_abs_ngram = [trigram_mod[bigram_mod[doc]] for doc in tokenized_abs]
423
+
424
+ topic_abs_str = [' '.join(doc) for doc in topic_abs_ngram]
425
+
426
+
427
+ X, vocabulary, vocab_dict = btm.get_words_freqs(topic_abs_str)
428
+ tf = np.array(X.sum(axis=0)).ravel()
429
+ docs_vec = btm.get_vectorized_docs(topic_abs, vocabulary)
430
+ docs_lens = list(map(len, docs_vec))
431
+ biterms = btm.get_biterms(docs_vec)
432
+
433
+ model = btm.BTM(X, vocabulary, seed=btm_seed, T=num_topic, M=20, alpha=50/8, beta=0.01)
434
+ model.fit(biterms, iterations=btm_iterations)
435
+
436
+ p_zd = model.transform(docs_vec)
437
+ coherence = model.coherence_
438
+ phi = tmp.get_phi(model)
439
+ topics_coords = tmp.prepare_coords(model)
440
+ totaltop = topics_coords.label.values.tolist()
441
+ perplexity = model.perplexity_
442
+ top_topics = model.df_words_topics_
443
+
444
+ return topics_coords, phi, totaltop, perplexity, top_topics
445
+
446
+ tab1, tab2, tab3, tab4 = st.tabs(["📈 Generate visualization", "📃 Reference", "📓 Recommended Reading", "⬇️ Download Help"])
447
+ with tab1:
448
+ try:
449
+ with st.spinner('Performing computations. Please wait ...'):
450
+ topics_coords, phi, totaltop, perplexity, top_topics = biterm_topic(extype)
451
+ col1, col2 = st.columns([4,6])
452
+
453
+ @st.cache_data(ttl=3600)
454
+ def biterm_map(extype):
455
+ btmvis_coords = tmp.plot_scatter_topics(topics_coords, size_col='size', label_col='label', topic=numvis)
456
+ return btmvis_coords
457
+
458
+ @st.cache_data(ttl=3600)
459
+ def biterm_bar(extype):
460
+ terms_probs = tmp.calc_terms_probs_ratio(phi, topic=numvis, lambda_=1)
461
+ btmvis_probs = tmp.plot_terms(terms_probs, font_size=12)
462
+ return btmvis_probs
463
+
464
+ with col1:
465
+ st.write('Perplexity score: ', perplexity)
466
+ st.write('')
467
+ numvis = st.selectbox(
468
+ 'Choose topic',
469
+ (totaltop), on_change=reset_biterm)
470
+ btmvis_coords = biterm_map(extype)
471
+ st.altair_chart(btmvis_coords)
472
+ with col2:
473
+ btmvis_probs = biterm_bar(extype)
474
+ st.altair_chart(btmvis_probs, use_container_width=True)
475
+
476
+ #===download results===#
477
+ resultcsv = top_topics.to_csv().encode("utf-8")
478
+ st.download_button(label = "Download Results", data=resultcsv, file_name="results.csv", mime="text\csv", on_click="ignore")
479
+
480
+ except ValueError as g:
481
+ st.error('🙇‍♂️ Please raise the number of topics and click submit')
482
+
483
+ except NameError as f:
484
+ st.warning('🖱️ Please click Submit')
485
+
486
+ with tab2:
487
+ st.markdown('**Yan, X., Guo, J., Lan, Y., & Cheng, X. (2013, May 13). A biterm topic model for short texts. Proceedings of the 22nd International Conference on World Wide Web.** https://doi.org/10.1145/2488388.2488514')
488
+ with tab3:
489
+ st.markdown('**Cai, M., Shah, N., Li, J., Chen, W. H., Cuomo, R. E., Obradovich, N., & Mackey, T. K. (2020, August 26). Identification and characterization of tweets related to the 2015 Indiana HIV outbreak: A retrospective infoveillance study. PLOS ONE, 15(8), e0235150.** https://doi.org/10.1371/journal.pone.0235150')
490
+ st.markdown('**Chen, Y., Dong, T., Ban, Q., & Li, Y. (2021). What Concerns Consumers about Hypertension? A Comparison between the Online Health Community and the Q&A Forum. International Journal of Computational Intelligence Systems, 14(1), 734.** https://doi.org/10.2991/ijcis.d.210203.002')
491
+ st.markdown('**George, Crissandra J., "AMBIGUOUS APPALACHIANNESS: A LINGUISTIC AND PERCEPTUAL INVESTIGATION INTO ARC-LABELED PENNSYLVANIA COUNTIES" (2022). Theses and Dissertations-- Linguistics. 48.** https://doi.org/10.13023/etd.2022.217')
492
+ st.markdown('**Li, J., Chen, W. H., Xu, Q., Shah, N., Kohler, J. C., & Mackey, T. K. (2020). Detection of self-reported experiences with corruption on twitter using unsupervised machine learning. Social Sciences & Humanities Open, 2(1), 100060.** https://doi.org/10.1016/j.ssaho.2020.100060')
493
+ with tab4:
494
+ st.subheader(':blue[Biterm]', anchor=False)
495
+ st.text("Click the three dots at the top right then select the desired format.")
496
+ st.markdown("![Downloading visualization](https://raw.githubusercontent.com/faizhalas/library-tools/main/images/download_biterm.jpg)")
497
+ st.divider()
498
+ st.subheader(':blue[Downloading CSV Results]', anchor=False)
499
+ st.button("Download Results")
500
+ st.text("Click Download results button at bottom of page")
501
+
502
+
503
+ #===BERTopic===
504
+ elif method == 'BERTopic':
505
+ @st.cache_resource(ttl = 3600, show_spinner=False)
506
+ #@st.cache_data(ttl=3600, show_spinner=False)
507
+ def bertopic_vis(extype):
508
+ umap_model = UMAP(n_neighbors=bert_n_neighbors, n_components=bert_n_components,
509
+ min_dist=0.0, metric='cosine', random_state=bert_random_state)
510
+ cluster_model = KMeans(n_clusters=num_topic)
511
+ if bert_embedding_model == 'all-MiniLM-L6-v2':
512
+ model = SentenceTransformer('all-MiniLM-L6-v2')
513
+ lang = 'en'
514
+ embeddings = model.encode(topic_abs, show_progress_bar=True)
515
+
516
+ elif bert_embedding_model == 'en_core_web_sm':
517
+ nlp = en_core_web_sm.load(exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
518
+ model = nlp
519
+ lang = 'en'
520
+ embeddings = np.array([nlp(text).vector for text in topic_abs])
521
+
522
+ elif bert_embedding_model == 'paraphrase-multilingual-MiniLM-L12-v2':
523
+ model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
524
+ lang = 'multilingual'
525
+ embeddings = model.encode(topic_abs, show_progress_bar=True)
526
+
527
+ representation_model = ""
528
+
529
+ if fine_tuning:
530
+ keybert = KeyBERTInspired()
531
+ mmr = MaximalMarginalRelevance(diversity=0.3)
532
+ representation_model = {
533
+ "KeyBERT": keybert,
534
+ "MMR": mmr,
535
+ }
536
+ if topic_labelling:
537
+ if llm_provider == "OpenAI/gpt-4o":
538
+ client = openai.OpenAI(api_key=api_key)
539
+ representation_model = {
540
+ "KeyBERT": keybert,
541
+ "MMR": mmr,
542
+ "test": OpenAI(client, model = "gpt-4o-mini", delay_in_seconds=10)
543
+ }
544
+ elif llm_provider == "Google/flan-t5":
545
+ pipe = pipeline("text2text-generation", model = "google/flan-t5-base")
546
+ clientmod = TextGeneration(pipe)
547
+ representation_model = {
548
+ "KeyBERT": keybert,
549
+ "MMR": mmr,
550
+ "test": clientmod
551
+ }
552
+ elif llm_provider == "LiquidAI/LFM2-350M":
553
+ pipe = pipeline("text-generation", model = "LiquidAI/LFM2-350M")
554
+ clientmod = TextGeneration(pipe)
555
+ representation_model = {
556
+ "KeyBERT": keybert,
557
+ "MMR": mmr,
558
+ "test": clientmod
559
+ }
560
+
561
+ vectorizer_model = CountVectorizer(ngram_range=(1, xgram), stop_words='english')
562
+ topic_model = BERTopic(representation_model = representation_model, embedding_model=model, hdbscan_model=cluster_model, language=lang, umap_model=umap_model, vectorizer_model=vectorizer_model, top_n_words=bert_top_n_words)
563
+ topics, probs = topic_model.fit_transform(topic_abs, embeddings=embeddings)
564
+
565
+ if(fine_tuning and topic_labelling):
566
+ generated_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["test"].values()]
567
+ topic_model.set_topic_labels(generated_labels)
568
+
569
+ return topic_model, topics, probs, embeddings
570
+
571
+ @st.cache_resource(ttl = 3600, show_spinner=False)
572
+ def Vis_Topics(extype):
573
+ fig1 = topic_model.visualize_topics(custom_labels = True)
574
+ return fig1
575
+ @st.cache_resource(ttl = 3600, show_spinner=False)
576
+ def Vis_Documents(extype):
577
+ fig2 = topic_model.visualize_document_datamap(topic_abs, embeddings=embeddings, custom_labels = True)
578
+ return fig2
579
+ @st.cache_resource(ttl = 3600, show_spinner=False)
580
+ def Vis_Hierarchy(extype):
581
+ fig3 = topic_model.visualize_hierarchy(top_n_topics=num_topic, custom_labels = True)
582
+ return fig3
583
+ @st.cache_resource(ttl = 3600, show_spinner=False)
584
+ def Vis_Heatmap(extype):
585
+ global topic_model
586
+ fig4 = topic_model.visualize_heatmap(n_clusters=num_topic-1, width=1000, height=1000, custom_labels = True)
587
+ return fig4
588
+ @st.cache_resource(ttl = 3600, show_spinner=False)
589
+ def Vis_Barchart(extype):
590
+ fig5 = topic_model.visualize_barchart(top_n_topics=num_topic, custom_labels = True)
591
+ return fig5
592
+
593
+ tab1, tab2, tab3, tab4 = st.tabs(["📈 Generate visualization", "📃 Reference", "📓 Recommended Reading", "⬇️ Download Help"])
594
+ with tab1:
595
+ try:
596
+ with st.spinner('Performing computations. Please wait ...'):
597
+
598
+ topic_model, topics, probs, embeddings = bertopic_vis(extype)
599
+ time.sleep(.5)
600
+ st.toast('Visualize Topics', icon='🏃')
601
+ fig1 = Vis_Topics(extype)
602
+
603
+ time.sleep(.5)
604
+ st.toast('Visualize Document', icon='🏃')
605
+ fig2 = Vis_Documents(extype)
606
+
607
+ time.sleep(.5)
608
+ st.toast('Visualize Document Hierarchy', icon='🏃')
609
+ fig3 = Vis_Hierarchy(extype)
610
+
611
+ time.sleep(.5)
612
+ st.toast('Visualize Topic Similarity', icon='🏃')
613
+ fig4 = Vis_Heatmap(extype)
614
+
615
+ time.sleep(.5)
616
+ st.toast('Visualize Terms', icon='🏃')
617
+ fig5 = Vis_Barchart(extype)
618
+
619
+ bertab1, bertab2, bertab3, bertab4, bertab5 = st.tabs(["Visualize Topics", "Visualize Terms", "Visualize Documents",
620
+ "Visualize Document Hierarchy", "Visualize Topic Similarity"])
621
+
622
+ with bertab1:
623
+ st.plotly_chart(fig1, use_container_width=True)
624
+ with bertab2:
625
+ st.plotly_chart(fig5, use_container_width=True)
626
+ with bertab3:
627
+ st.plotly_chart(fig2, use_container_width=True)
628
+ with bertab4:
629
+ st.plotly_chart(fig3, use_container_width=True)
630
+ with bertab5:
631
+ st.plotly_chart(fig4, use_container_width=True)
632
+
633
+ #===download results===#
634
+ results = topic_model.get_topic_info()
635
+ resultf = pd.DataFrame(results)
636
+ resultcsv = resultf.to_csv().encode("utf-8")
637
+ st.download_button(
638
+ label = "Download Results",
639
+ data=resultcsv,
640
+ file_name="results.csv",
641
+ mime="text\csv",
642
+ on_click="ignore",
643
+ )
644
+
645
+ except ValueError:
646
+ st.error('🙇‍♂️ Please raise the number of topics and click submit')
647
+
648
+
649
+ except NameError:
650
+ st.warning('🖱️ Please click Submit')
651
+
652
+ with tab2:
653
+ st.markdown('**Grootendorst, M. (2022). BERTopic: Neural topic modeling with a class-based TF-IDF procedure. arXiv preprint arXiv:2203.05794.** https://doi.org/10.48550/arXiv.2203.05794')
654
+
655
+ with tab3:
656
+ st.markdown('**Jeet Rawat, A., Ghildiyal, S., & Dixit, A. K. (2022, December 1). Topic modelling of legal documents using NLP and bidirectional encoder representations from transformers. Indonesian Journal of Electrical Engineering and Computer Science, 28(3), 1749.** https://doi.org/10.11591/ijeecs.v28.i3.pp1749-1755')
657
+ st.markdown('**Yao, L. F., Ferawati, K., Liew, K., Wakamiya, S., & Aramaki, E. (2023, April 20). Disruptions in the Cystic Fibrosis Community’s Experiences and Concerns During the COVID-19 Pandemic: Topic Modeling and Time Series Analysis of Reddit Comments. Journal of Medical Internet Research, 25, e45249.** https://doi.org/10.2196/45249')
658
+
659
+ with tab4:
660
+ st.divider()
661
+ st.subheader(':blue[BERTopic]', anchor=False)
662
+ st.text("Click the camera icon on the top right menu")
663
+ st.markdown("![Downloading visualization](https://raw.githubusercontent.com/faizhalas/library-tools/main/images/download_bertopic.jpg)")
664
+ st.divider()
665
+ st.subheader(':blue[Downloading CSV Results]', anchor=False)
666
+ st.button("Download Results")
667
+ st.text("Click Download results button at bottom of page")
668
+
669
+ except:
670
+ st.error("Please ensure that your file is correct. Please contact us if you find that this is an error.", icon="🚨")
671
+ st.stop()