faizhalas commited on
Commit
35fca6a
β€’
1 Parent(s): 96e879c

Adding button to prevent crash

Browse files
Files changed (1) hide show
  1. pages/2 Topic Modeling.py +132 -110
pages/2 Topic Modeling.py CHANGED
@@ -132,49 +132,56 @@ if uploaded_file is not None:
132
  papers = conv_txt(extype)
133
 
134
  topic_abs, paper=clean_csv(extype)
135
- method = st.selectbox(
 
136
  'Choose method',
137
- ('Choose...', 'pyLDA', 'Biterm','BERTopic'), on_change=reset_all)
138
-
 
 
 
 
139
  #===topic===
140
  if method == 'Choose...':
141
  st.write('')
142
 
143
- elif method == 'pyLDA':
144
- num_topic = st.slider('Choose number of topics', min_value=2, max_value=15, step=1, on_change=reset_all)
145
- @st.cache_data(ttl=3600, show_spinner=False)
146
- def pylda(extype):
147
- topic_abs_LDA = [t.split(' ') for t in topic_abs]
148
- id2word = Dictionary(topic_abs_LDA)
149
- corpus = [id2word.doc2bow(text) for text in topic_abs_LDA]
150
- #===LDA===
151
- lda_model = LdaModel(corpus=corpus,
152
- id2word=id2word,
153
- num_topics=num_topic,
154
- random_state=0,
155
- chunksize=100,
156
- alpha='auto',
157
- per_word_topics=True)
158
-
159
- pprint(lda_model.print_topics())
160
- doc_lda = lda_model[corpus]
161
-
162
- #===visualization===
163
- coherence_model_lda = CoherenceModel(model=lda_model, texts=topic_abs_LDA, dictionary=id2word, coherence='c_v')
164
- coherence_lda = coherence_model_lda.get_coherence()
165
- vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
166
- py_lda_vis_html = pyLDAvis.prepared_data_to_html(vis)
167
- return py_lda_vis_html, coherence_lda
168
-
169
  tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Generate visualization & Calculate coherence", "πŸ“ƒ Reference", "πŸ““ Recommended Reading"])
170
 
171
  with tab1:
172
  #===visualization===
173
- with st.spinner('Calculating and Creating pyLDAvis Visualization ...'):
174
- py_lda_vis_html, coherence_lda = pylda(extype)
175
- st.write('Coherence: ', (coherence_lda))
176
- components.html(py_lda_vis_html, width=1700, height=800)
177
- st.markdown('Copyright (c) 2015, Ben Mabey. https://github.com/bmabey/pyLDAvis')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  with tab2:
180
  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')
@@ -186,10 +193,10 @@ if uploaded_file is not None:
186
  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')
187
 
188
  #===Biterm===
189
- elif method == 'Biterm':
190
- num_bitopic = st.slider('Choose number of topics', min_value=2, max_value=20, step=1, on_change=reset_all)
191
  #===optimize Biterm===
192
- @st.cache_data(ttl=3600)
193
  def biterm_topic(extype):
194
  X, vocabulary, vocab_dict = btm.get_words_freqs(topic_abs)
195
  tf = np.array(X.sum(axis=0)).ravel()
@@ -197,7 +204,7 @@ if uploaded_file is not None:
197
  docs_lens = list(map(len, docs_vec))
198
  biterms = btm.get_biterms(docs_vec)
199
  model = btm.BTM(
200
- X, vocabulary, seed=12321, T=num_bitopic, M=20, alpha=50/8, beta=0.01)
201
  model.fit(biterms, iterations=20)
202
  p_zd = model.transform(docs_vec)
203
  coherence = model.coherence_
@@ -206,84 +213,85 @@ if uploaded_file is not None:
206
  totaltop = topics_coords.label.values.tolist()
207
  return topics_coords, phi, totaltop
208
 
209
- try:
210
- topics_coords, phi, totaltop = biterm_topic(extype)
211
- #with st.spinner('Visualizing, please wait ....'):
212
- tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Generate visualization", "πŸ“ƒ Reference", "πŸ““ Recommended Reading"])
213
- with tab1:
214
- col1, col2 = st.columns(2)
215
-
216
- @st.cache_data(ttl=3600)
217
- def biterm_map(extype):
218
- btmvis_coords = tmp.plot_scatter_topics(topics_coords, size_col='size', label_col='label', topic=numvis)
219
- return btmvis_coords
220
-
221
- @st.cache_data(ttl=3600)
222
- def biterm_bar(extype):
223
- terms_probs = tmp.calc_terms_probs_ratio(phi, topic=numvis, lambda_=1)
224
- btmvis_probs = tmp.plot_terms(terms_probs, font_size=12)
225
- return btmvis_probs
226
 
227
- with col1:
228
- numvis = st.selectbox(
229
- 'Choose topic',
230
- (totaltop), on_change=reset_biterm)
231
- btmvis_coords = biterm_map(extype)
232
- st.altair_chart(btmvis_coords, use_container_width=True)
233
- with col2:
234
- btmvis_probs = biterm_bar(extype)
235
- st.altair_chart(btmvis_probs, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- with tab2:
238
  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')
239
- with tab3:
240
  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')
241
  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')
242
  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')
243
  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')
244
 
245
- except ValueError:
246
- st.error('Please raise the number of topics')
247
-
248
  #===BERTopic===
249
  elif method == 'BERTopic':
250
- num_btopic = st.slider('Choose number of topics', min_value=4, max_value=20, step=1, on_change=reset_all)
251
- @st.cache_data(ttl=3600)
252
  def bertopic_vis(extype):
253
  topic_time = paper.Year.values.tolist()
254
- cluster_model = KMeans(n_clusters=num_btopic)
255
  nlp = en_core_web_sm.load(exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
256
  topic_model = BERTopic(embedding_model=nlp, hdbscan_model=cluster_model, language="multilingual").fit(topic_abs)
257
  topics, probs = topic_model.fit_transform(topic_abs)
258
  return topic_model, topic_time, topics, probs
259
 
260
- @st.cache_data(ttl=3600)
261
  def Vis_Topics(extype):
262
  fig1 = topic_model.visualize_topics()
263
  return fig1
264
 
265
- @st.cache_data(ttl=3600)
266
  def Vis_Documents(extype):
267
  fig2 = topic_model.visualize_documents(topic_abs)
268
  return fig2
269
 
270
- @st.cache_data(ttl=3600)
271
  def Vis_Hierarchy(extype):
272
- fig3 = topic_model.visualize_hierarchy(top_n_topics=num_btopic)
273
  return fig3
274
 
275
- @st.cache_data(ttl=3600)
276
  def Vis_Heatmap(extype):
277
  global topic_model
278
- fig4 = topic_model.visualize_heatmap(n_clusters=num_btopic-1, width=1000, height=1000)
279
  return fig4
280
 
281
- @st.cache_data(ttl=3600)
282
  def Vis_Barchart(extype):
283
- fig5 = topic_model.visualize_barchart(top_n_topics=num_btopic, n_words=10)
284
  return fig5
285
 
286
- @st.cache_data(ttl=3600)
287
  def Vis_ToT(extype):
288
  topics_over_time = topic_model.topics_over_time(topic_abs, topic_time)
289
  fig6 = topic_model.visualize_topics_over_time(topics_over_time)
@@ -291,35 +299,49 @@ if uploaded_file is not None:
291
 
292
  tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Generate visualization", "πŸ“ƒ Reference", "πŸ““ Recommended Reading"])
293
  with tab1:
294
- topic_model, topic_time, topics, probs = bertopic_vis(extype)
295
- #===visualization===
296
- viz = st.selectbox(
297
- 'Choose visualization',
298
- ('Visualize Topics', 'Visualize Documents', 'Visualize Document Hierarchy', 'Visualize Topic Similarity', 'Visualize Terms', 'Visualize Topics over Time'))
299
-
300
- if viz == 'Visualize Topics':
301
- fig1 = Vis_Topics(extype)
302
- st.write(fig1)
303
-
304
- elif viz == 'Visualize Documents':
305
- fig2 = Vis_Documents(extype)
306
- st.write(fig2)
307
-
308
- elif viz == 'Visualize Document Hierarchy':
309
- fig3 = Vis_Hierarchy(extype)
310
- st.write(fig3)
311
-
312
- elif viz == 'Visualize Topic Similarity':
313
- fig4 = Vis_Heatmap(extype)
314
- st.write(fig4)
315
-
316
- elif viz == 'Visualize Terms':
317
- fig5 = Vis_Barchart(extype)
318
- st.write(fig5)
319
-
320
- elif viz == 'Visualize Topics over Time':
321
- fig6 = Vis_ToT(extype)
322
- st.write(fig6)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
  with tab2:
325
  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')
 
132
  papers = conv_txt(extype)
133
 
134
  topic_abs, paper=clean_csv(extype)
135
+ c1, c2 = st.columns([5,5])
136
+ method = c1.selectbox(
137
  'Choose method',
138
+ ('Choose...', 'pyLDA', 'Biterm', 'BERTopic'), on_change=reset_all)
139
+ c1.info("Don't do anything during the computing", icon="⚠️")
140
+ num_cho = c2.number_input('Choose number of topics', min_value=2, max_value=30, value=2)
141
+ if c2.button("Submit", on_click=reset_all):
142
+ num_topic = num_cho
143
+
144
  #===topic===
145
  if method == 'Choose...':
146
  st.write('')
147
 
148
+ elif method == 'pyLDA':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Generate visualization & Calculate coherence", "πŸ“ƒ Reference", "πŸ““ Recommended Reading"])
150
 
151
  with tab1:
152
  #===visualization===
153
+ @st.cache_data(ttl=3600, show_spinner=False)
154
+ def pylda(extype):
155
+ topic_abs_LDA = [t.split(' ') for t in topic_abs]
156
+ id2word = Dictionary(topic_abs_LDA)
157
+ corpus = [id2word.doc2bow(text) for text in topic_abs_LDA]
158
+ #===LDA===
159
+ lda_model = LdaModel(corpus=corpus,
160
+ id2word=id2word,
161
+ num_topics=num_topic,
162
+ random_state=0,
163
+ chunksize=100,
164
+ alpha='auto',
165
+ per_word_topics=True)
166
+
167
+ pprint(lda_model.print_topics())
168
+ doc_lda = lda_model[corpus]
169
+
170
+ #===visualization===
171
+ coherence_model_lda = CoherenceModel(model=lda_model, texts=topic_abs_LDA, dictionary=id2word, coherence='c_v')
172
+ coherence_lda = coherence_model_lda.get_coherence()
173
+ vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
174
+ py_lda_vis_html = pyLDAvis.prepared_data_to_html(vis)
175
+ return py_lda_vis_html, coherence_lda
176
+
177
+ with st.spinner('Performing computations. Please wait ...'):
178
+ try:
179
+ py_lda_vis_html, coherence_lda = pylda(extype)
180
+ st.write('Coherence: ', (coherence_lda))
181
+ components.html(py_lda_vis_html, width=1700, height=800)
182
+ st.markdown('Copyright (c) 2015, Ben Mabey. https://github.com/bmabey/pyLDAvis')
183
+ except NameError:
184
+ st.error('πŸ–±οΈ Please click Submit')
185
 
186
  with tab2:
187
  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')
 
193
  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')
194
 
195
  #===Biterm===
196
+ elif method == 'Biterm':
197
+
198
  #===optimize Biterm===
199
+ @st.cache_data(ttl=3600, show_spinner=False)
200
  def biterm_topic(extype):
201
  X, vocabulary, vocab_dict = btm.get_words_freqs(topic_abs)
202
  tf = np.array(X.sum(axis=0)).ravel()
 
204
  docs_lens = list(map(len, docs_vec))
205
  biterms = btm.get_biterms(docs_vec)
206
  model = btm.BTM(
207
+ X, vocabulary, seed=12321, T=num_topic, M=20, alpha=50/8, beta=0.01)
208
  model.fit(biterms, iterations=20)
209
  p_zd = model.transform(docs_vec)
210
  coherence = model.coherence_
 
213
  totaltop = topics_coords.label.values.tolist()
214
  return topics_coords, phi, totaltop
215
 
216
+ tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Generate visualization", "πŸ“ƒ Reference", "πŸ““ Recommended Reading"])
217
+ with tab1:
218
+ try:
219
+ with st.spinner('Performing computations. Please wait ...'):
220
+ topics_coords, phi, totaltop = biterm_topic(extype)
221
+ col1, col2 = st.columns([4,6])
 
 
 
 
 
 
 
 
 
 
 
222
 
223
+ @st.cache_data(ttl=3600)
224
+ def biterm_map(extype):
225
+ btmvis_coords = tmp.plot_scatter_topics(topics_coords, size_col='size', label_col='label', topic=numvis)
226
+ return btmvis_coords
227
+
228
+ @st.cache_data(ttl=3600)
229
+ def biterm_bar(extype):
230
+ terms_probs = tmp.calc_terms_probs_ratio(phi, topic=numvis, lambda_=1)
231
+ btmvis_probs = tmp.plot_terms(terms_probs, font_size=12)
232
+ return btmvis_probs
233
+
234
+ with col1:
235
+ numvis = st.selectbox(
236
+ 'Choose topic',
237
+ (totaltop), on_change=reset_biterm)
238
+ btmvis_coords = biterm_map(extype)
239
+ st.altair_chart(btmvis_coords)
240
+ with col2:
241
+ btmvis_probs = biterm_bar(extype)
242
+ st.altair_chart(btmvis_probs, use_container_width=True)
243
+
244
+ except ValueError:
245
+ st.error('πŸ™‡β€β™‚οΈ Please raise the number of topics and click submit')
246
+ except NameError:
247
+ st.error('πŸ–±οΈ Please click Submit')
248
 
249
+ with tab2:
250
  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')
251
+ with tab3:
252
  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')
253
  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')
254
  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')
255
  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')
256
 
 
 
 
257
  #===BERTopic===
258
  elif method == 'BERTopic':
259
+ @st.cache_data(ttl=3600, show_spinner=False)
 
260
  def bertopic_vis(extype):
261
  topic_time = paper.Year.values.tolist()
262
+ cluster_model = KMeans(n_clusters=num_topic)
263
  nlp = en_core_web_sm.load(exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
264
  topic_model = BERTopic(embedding_model=nlp, hdbscan_model=cluster_model, language="multilingual").fit(topic_abs)
265
  topics, probs = topic_model.fit_transform(topic_abs)
266
  return topic_model, topic_time, topics, probs
267
 
268
+ @st.cache_data(ttl=3600, show_spinner=False)
269
  def Vis_Topics(extype):
270
  fig1 = topic_model.visualize_topics()
271
  return fig1
272
 
273
+ @st.cache_data(ttl=3600, show_spinner=False)
274
  def Vis_Documents(extype):
275
  fig2 = topic_model.visualize_documents(topic_abs)
276
  return fig2
277
 
278
+ @st.cache_data(ttl=3600, show_spinner=False)
279
  def Vis_Hierarchy(extype):
280
+ fig3 = topic_model.visualize_hierarchy(top_n_topics=num_topic)
281
  return fig3
282
 
283
+ @st.cache_data(ttl=3600, show_spinner=False)
284
  def Vis_Heatmap(extype):
285
  global topic_model
286
+ fig4 = topic_model.visualize_heatmap(n_clusters=num_topic-1, width=1000, height=1000)
287
  return fig4
288
 
289
+ @st.cache_data(ttl=3600, show_spinner=False)
290
  def Vis_Barchart(extype):
291
+ fig5 = topic_model.visualize_barchart(top_n_topics=num_topic, n_words=10)
292
  return fig5
293
 
294
+ @st.cache_data(ttl=3600, show_spinner=False)
295
  def Vis_ToT(extype):
296
  topics_over_time = topic_model.topics_over_time(topic_abs, topic_time)
297
  fig6 = topic_model.visualize_topics_over_time(topics_over_time)
 
299
 
300
  tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Generate visualization", "πŸ“ƒ Reference", "πŸ““ Recommended Reading"])
301
  with tab1:
302
+ try:
303
+ with st.spinner('Performing computations. Please wait ...'):
304
+ topic_model, topic_time, topics, probs = bertopic_vis(extype)
305
+ #===visualization===
306
+ viz = st.selectbox(
307
+ 'Choose visualization',
308
+ ('Visualize Topics', 'Visualize Documents', 'Visualize Document Hierarchy', 'Visualize Topic Similarity', 'Visualize Terms', 'Visualize Topics over Time'))
309
+
310
+ if viz == 'Visualize Topics':
311
+ with st.spinner('Performing computations. Please wait ...'):
312
+ fig1 = Vis_Topics(extype)
313
+ st.write(fig1)
314
+
315
+ elif viz == 'Visualize Documents':
316
+ with st.spinner('Performing computations. Please wait ...'):
317
+ fig2 = Vis_Documents(extype)
318
+ st.write(fig2)
319
+
320
+ elif viz == 'Visualize Document Hierarchy':
321
+ with st.spinner('Performing computations. Please wait ...'):
322
+ fig3 = Vis_Hierarchy(extype)
323
+ st.write(fig3)
324
+
325
+ elif viz == 'Visualize Topic Similarity':
326
+ with st.spinner('Performing computations. Please wait ...'):
327
+ fig4 = Vis_Heatmap(extype)
328
+ st.write(fig4)
329
+
330
+ elif viz == 'Visualize Terms':
331
+ with st.spinner('Performing computations. Please wait ...'):
332
+ fig5 = Vis_Barchart(extype)
333
+ st.write(fig5)
334
+
335
+ elif viz == 'Visualize Topics over Time':
336
+ with st.spinner('Performing computations. Please wait ...'):
337
+ fig6 = Vis_ToT(extype)
338
+ st.write(fig6)
339
+
340
+ except ValueError:
341
+ st.error('πŸ™‡β€β™‚οΈ Please raise the number of topics and click submit')
342
+
343
+ except NameError:
344
+ st.error('πŸ–±οΈ Please click Submit')
345
 
346
  with tab2:
347
  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')