Spaces:
Running
Running
File size: 68,063 Bytes
f742eb8 c837e02 13d6d96 c837e02 13d6d96 c837e02 13d6d96 c837e02 13d6d96 c837e02 13d6d96 c837e02 13d6d96 c837e02 13d6d96 cd8b282 13d6d96 cd8b282 c837e02 13d6d96 c837e02 f742eb8 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 9cc6596 e3473f2 f742eb8 |
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 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 |
<<<<<<< HEAD
#import module
import streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import numpy as np
import re
import string
import nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
nltk.download('stopwords')
from nltk.corpus import stopwords
import gensim
import gensim.corpora as corpora
from gensim.corpora import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from pprint import pprint
import pickle
import pyLDAvis
import pyLDAvis.gensim_models as gensimvis
from io import StringIO
from ipywidgets.embed import embed_minimal_html
from nltk.stem.snowball import SnowballStemmer
from bertopic import BERTopic
from bertopic.representation import KeyBERTInspired, MaximalMarginalRelevance, OpenAI, TextGeneration
import plotly.express as px
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import CountVectorizer
import bitermplus as btm
import tmplot as tmp
import tomotopy
import sys
import spacy
import en_core_web_sm
import pipeline
from html2image import Html2Image
from umap import UMAP
import os
import time
import json
from tools import sourceformat as sf
import datamapplot
from sentence_transformers import SentenceTransformer
import openai
from transformers import pipeline
#===config===
st.set_page_config(
page_title="Coconut",
page_icon="๐ฅฅ",
layout="wide",
initial_sidebar_state="collapsed"
)
hide_streamlit_style = """
<style>
#MainMenu
{visibility: hidden;}
footer {visibility: hidden;}
[data-testid="collapsedControl"] {display: none}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
with st.popover("๐ Menu"):
st.page_link("https://www.coconut-libtool.com/", label="Home", icon="๐ ")
st.page_link("pages/1 Scattertext.py", label="Scattertext", icon="1๏ธโฃ")
st.page_link("pages/2 Topic Modeling.py", label="Topic Modeling", icon="2๏ธโฃ")
st.page_link("pages/3 Bidirected Network.py", label="Bidirected Network", icon="3๏ธโฃ")
st.page_link("pages/4 Sunburst.py", label="Sunburst", icon="4๏ธโฃ")
st.page_link("pages/5 Burst Detection.py", label="Burst Detection", icon="5๏ธโฃ")
st.page_link("pages/6 Keywords Stem.py", label="Keywords Stem", icon="6๏ธโฃ")
st.page_link("pages/7 Sentiment Analysis.py", label="Sentiment Analysis", icon="7๏ธโฃ")
st.page_link("pages/8 Shifterator.py", label="Shifterator", icon="8๏ธโฃ")
st.page_link("pages/9 Summarization.py", label = "Summarization",icon ="9๏ธโฃ")
st.page_link("pages/10 WordCloud.py", label = "WordCloud", icon = "๐")
st.header("Topic Modeling", anchor=False)
st.subheader('Put your file here...', anchor=False)
#========unique id========
@st.cache_resource(ttl=3600)
def create_list():
l = [1, 2, 3]
return l
l = create_list()
first_list_value = l[0]
l[0] = first_list_value + 1
uID = str(l[0])
@st.cache_data(ttl=3600)
def get_ext(uploaded_file):
extype = uID+uploaded_file.name
return extype
#===clear cache===
def reset_biterm():
try:
biterm_map.clear()
biterm_bar.clear()
except NameError:
biterm_topic.clear()
def reset_all():
st.cache_data.clear()
#===avoiding deadlock===
os.environ["TOKENIZERS_PARALLELISM"] = "false"
#===upload file===
@st.cache_data(ttl=3600)
def upload(file):
papers = pd.read_csv(uploaded_file)
if "About the data" in papers.columns[0]:
papers = sf.dim(papers)
col_dict = {'MeSH terms': 'Keywords',
'PubYear': 'Year',
'Times cited': 'Cited by',
'Publication Type': 'Document Type'
}
papers.rename(columns=col_dict, inplace=True)
return papers
@st.cache_data(ttl=3600)
def conv_txt(extype):
if("PMID" in (uploaded_file.read()).decode()):
uploaded_file.seek(0)
papers = sf.medline(uploaded_file)
print(papers)
return papers
col_dict = {'TI': 'Title',
'SO': 'Source title',
'DE': 'Author Keywords',
'DT': 'Document Type',
'AB': 'Abstract',
'TC': 'Cited by',
'PY': 'Year',
'ID': 'Keywords Plus',
'rights_date_used': 'Year'}
uploaded_file.seek(0)
papers = pd.read_csv(uploaded_file, sep='\t')
if("htid" in papers.columns):
papers = sf.htrc(papers)
papers.rename(columns=col_dict, inplace=True)
print(papers)
return papers
@st.cache_data(ttl=3600)
def conv_json(extype):
col_dict={'title': 'title',
'rights_date_used': 'Year',
}
data = json.load(uploaded_file)
hathifile = data['gathers']
keywords = pd.DataFrame.from_records(hathifile)
keywords = sf.htrc(keywords)
keywords.rename(columns=col_dict,inplace=True)
return keywords
@st.cache_resource(ttl=3600)
def conv_pub(extype):
if (get_ext(extype)).endswith('.tar.gz'):
bytedata = extype.read()
keywords = sf.readPub(bytedata)
elif (get_ext(extype)).endswith('.xml'):
bytedata = extype.read()
keywords = sf.readxml(bytedata)
return keywords
#===Read data===
uploaded_file = st.file_uploader('', type=['csv', 'txt','json','tar.gz','xml'], on_change=reset_all)
if uploaded_file is not None:
try:
extype = get_ext(uploaded_file)
if extype.endswith('.csv'):
papers = upload(extype)
elif extype.endswith('.txt'):
papers = conv_txt(extype)
elif extype.endswith('.json'):
papers = conv_json(extype)
elif extype.endswith('.tar.gz') or extype.endswith('.xml'):
papers = conv_pub(uploaded_file)
coldf = sorted(papers.select_dtypes(include=['object']).columns.tolist())
c1, c2, c3 = st.columns([3,3,4])
method = c1.selectbox(
'Choose method',
('Choose...', 'pyLDA', 'Biterm', 'BERTopic'))
ColCho = c2.selectbox('Choose column', (["Abstract","Title", "Abstract + Title"]))
num_cho = c3.number_input('Choose number of topics', min_value=2, max_value=30, value=5)
d1, d2 = st.columns([3,7])
xgram = d1.selectbox("N-grams", ("1", "2", "3"))
xgram = int(xgram)
words_to_remove = d2.text_input("Remove specific words. Separate words by semicolons (;)")
rem_copyright = d1.toggle('Remove copyright statement', value=True)
rem_punc = d2.toggle('Remove punctuation', value=True)
#===advance settings===
with st.expander("๐งฎ Show advance settings"):
t1, t2, t3 = st.columns([3,3,4])
if method == 'pyLDA':
py_random_state = t1.number_input('Random state', min_value=0, max_value=None, step=1)
py_chunksize = t2.number_input('Chunk size', value=100 , min_value=10, max_value=None, step=1)
opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
elif method == 'Biterm':
btm_seed = t1.number_input('Random state seed', value=100 , min_value=1, max_value=None, step=1)
btm_iterations = t2.number_input('Iterations number', value=20 , min_value=2, max_value=None, step=1)
opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
elif method == 'BERTopic':
u1, u2 = st.columns([5,5])
bert_top_n_words = u1.number_input('top_n_words', value=5 , min_value=5, max_value=25, step=1)
bert_random_state = u2.number_input('random_state', value=42 , min_value=1, max_value=None, step=1)
bert_n_components = u1.number_input('n_components', value=5 , min_value=1, max_value=None, step=1)
bert_n_neighbors = u2.number_input('n_neighbors', value=15 , min_value=1, max_value=None, step=1)
bert_embedding_model = st.radio(
"embedding_model",
["all-MiniLM-L6-v2", "paraphrase-multilingual-MiniLM-L12-v2", "en_core_web_sm"], index=0, horizontal=True)
fine_tuning = st.toggle("Use Fine-tuning")
if fine_tuning:
topic_labelling = st.toggle("Automatic topic labelling")
if topic_labelling:
llm_provider = st.selectbox("Model",["OpenAI/gpt-4o","Google/flan-t5","LiquidAI/LFM2-350M"])
if llm_provider == "OpenAI/gpt-4o":
api_key = st.text_input("API Key")
else:
st.write('Please choose your preferred method')
#===clean csv===
@st.cache_data(ttl=3600, show_spinner=False)
def clean_csv(extype):
if (ColCho=="Abstract + Title"):
papers["Abstract + Title"] = papers["Title"] + " " + papers["Abstract"]
st.write(papers["Abstract + Title"])
paper = papers.dropna(subset=[ColCho])
#===mapping===
paper['Abstract_pre'] = paper[ColCho].map(lambda x: x.lower())
if rem_punc:
paper['Abstract_pre'] = paper['Abstract_pre'].map(
lambda x: re.sub(f"[{re.escape(string.punctuation)}]", " ", x)
).map(lambda x: re.sub(r"\s+", " ", x).strip())
paper['Abstract_pre'] = paper['Abstract_pre'].str.replace('[\u2018\u2019\u201c\u201d]', '', regex=True)
if rem_copyright:
paper['Abstract_pre'] = paper['Abstract_pre'].map(lambda x: re.sub('ยฉ.*', '', x))
#===stopword removal===
stop = stopwords.words('english')
paper['Abstract_stop'] = paper['Abstract_pre'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
#===lemmatize===
lemmatizer = WordNetLemmatizer()
@st.cache_resource(ttl=3600)
def lemmatize_words(text):
words = text.split()
words = [lemmatizer.lemmatize(word) for word in words]
return ' '.join(words)
paper['Abstract_lem'] = paper['Abstract_stop'].apply(lemmatize_words)
words_rmv = [word.strip() for word in words_to_remove.split(";")]
remove_dict = {word: None for word in words_rmv}
@st.cache_resource(ttl=3600)
def remove_words(text):
words = text.split()
cleaned_words = [word for word in words if word not in remove_dict]
return ' '.join(cleaned_words)
paper['Abstract_lem'] = paper['Abstract_lem'].map(remove_words)
topic_abs = paper.Abstract_lem.values.tolist()
return topic_abs, paper
topic_abs, paper=clean_csv(extype)
if st.button("Submit", on_click=reset_all):
num_topic = num_cho
if method == 'BERTopic':
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="โน๏ธ")
#===topic===
if method == 'Choose...':
st.write('')
elif method == 'pyLDA':
tab1, tab2, tab3, tab4 = st.tabs(["๐ Generate visualization", "๐ Reference", "๐ Recommended Reading", "โฌ๏ธ Download Help"])
with tab1:
#===visualization===
@st.cache_data(ttl=3600, show_spinner=False)
def pylda(extype):
topic_abs_LDA = [t.split(' ') for t in topic_abs]
bigram = Phrases(topic_abs_LDA, min_count=xgram, threshold=opt_threshold)
trigram = Phrases(bigram[topic_abs_LDA], threshold=opt_threshold)
bigram_mod = Phraser(bigram)
trigram_mod = Phraser(trigram)
topic_abs_LDA = [trigram_mod[bigram_mod[doc]] for doc in topic_abs_LDA]
id2word = Dictionary(topic_abs_LDA)
corpus = [id2word.doc2bow(text) for text in topic_abs_LDA]
#===LDA===
lda_model = LdaModel(corpus=corpus,
id2word=id2word,
num_topics=num_topic,
random_state=py_random_state,
chunksize=py_chunksize,
alpha='auto',
per_word_topics=False)
pprint(lda_model.print_topics())
doc_lda = lda_model[corpus]
topics = lda_model.show_topics(num_words = 30,formatted=False)
#===visualization===
coherence_model_lda = CoherenceModel(model=lda_model, texts=topic_abs_LDA, dictionary=id2word, coherence='c_v')
coherence_lda = coherence_model_lda.get_coherence()
vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
py_lda_vis_html = pyLDAvis.prepared_data_to_html(vis)
return py_lda_vis_html, coherence_lda, vis, topics
with st.spinner('Performing computations. Please wait ...'):
try:
py_lda_vis_html, coherence_lda, vis, topics = pylda(extype)
st.write('Coherence score: ', coherence_lda)
components.html(py_lda_vis_html, width=1500, height=800)
st.markdown('Copyright (c) 2015, Ben Mabey. https://github.com/bmabey/pyLDAvis')
@st.cache_data(ttl=3600, show_spinner=False)
def img_lda(vis):
pyLDAvis.save_html(vis, 'output.html')
hti = Html2Image()
hti.browser.flags = ['--default-background-color=ffffff', '--hide-scrollbars']
hti.browser.use_new_headless = None
css = "body {background: white;}"
hti.screenshot(
other_file='output.html', css_str=css, size=(1500, 800),
save_as='ldavis_img.png'
)
img_lda(vis)
d1, d2 = st.columns(2)
with open("ldavis_img.png", "rb") as file:
btn = d1.download_button(
label="Download image",
data=file,
file_name="ldavis_img.png",
mime="image/png"
)
#===download results===#
resultf = pd.DataFrame(topics)
#formatting
resultf = resultf.transpose()
resultf = resultf.drop([0])
resultf = resultf.explode(list(range(len(resultf.columns))), ignore_index=False)
resultcsv = resultf.to_csv().encode("utf-8")
d2.download_button(
label = "Download Results",
data=resultcsv,
file_name="results.csv",
mime="text\csv",
on_click="ignore")
except NameError as f:
st.warning('๐ฑ๏ธ Please click Submit')
with tab2:
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')
with tab3:
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')
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')
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')
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')
with tab4:
st.subheader(':blue[pyLDA]', anchor=False)
st.button('Download image')
st.text("Click Download Image button.")
st.divider()
st.subheader(':blue[Downloading CSV Results]', anchor=False)
st.button("Download Results")
st.text("Click Download results button at bottom of page")
#===Biterm===
elif method == 'Biterm':
#===optimize Biterm===
@st.cache_data(ttl=3600, show_spinner=False)
def biterm_topic(extype):
tokenized_abs = [t.split(' ') for t in topic_abs]
bigram = Phrases(tokenized_abs, min_count=xgram, threshold=opt_threshold)
trigram = Phrases(bigram[tokenized_abs], threshold=opt_threshold)
bigram_mod = Phraser(bigram)
trigram_mod = Phraser(trigram)
topic_abs_ngram = [trigram_mod[bigram_mod[doc]] for doc in tokenized_abs]
topic_abs_str = [' '.join(doc) for doc in topic_abs_ngram]
X, vocabulary, vocab_dict = btm.get_words_freqs(topic_abs_str)
tf = np.array(X.sum(axis=0)).ravel()
docs_vec = btm.get_vectorized_docs(topic_abs, vocabulary)
docs_lens = list(map(len, docs_vec))
biterms = btm.get_biterms(docs_vec)
model = btm.BTM(X, vocabulary, seed=btm_seed, T=num_topic, M=20, alpha=50/8, beta=0.01)
model.fit(biterms, iterations=btm_iterations)
p_zd = model.transform(docs_vec)
coherence = model.coherence_
phi = tmp.get_phi(model)
topics_coords = tmp.prepare_coords(model)
totaltop = topics_coords.label.values.tolist()
perplexity = model.perplexity_
top_topics = model.df_words_topics_
return topics_coords, phi, totaltop, perplexity, top_topics
tab1, tab2, tab3, tab4 = st.tabs(["๐ Generate visualization", "๐ Reference", "๐ Recommended Reading", "โฌ๏ธ Download Help"])
with tab1:
try:
with st.spinner('Performing computations. Please wait ...'):
topics_coords, phi, totaltop, perplexity, top_topics = biterm_topic(extype)
col1, col2 = st.columns([4,6])
@st.cache_data(ttl=3600)
def biterm_map(extype):
btmvis_coords = tmp.plot_scatter_topics(topics_coords, size_col='size', label_col='label', topic=numvis)
return btmvis_coords
@st.cache_data(ttl=3600)
def biterm_bar(extype):
terms_probs = tmp.calc_terms_probs_ratio(phi, topic=numvis, lambda_=1)
btmvis_probs = tmp.plot_terms(terms_probs, font_size=12)
return btmvis_probs
with col1:
st.write('Perplexity score: ', perplexity)
st.write('')
numvis = st.selectbox(
'Choose topic',
(totaltop), on_change=reset_biterm)
btmvis_coords = biterm_map(extype)
st.altair_chart(btmvis_coords)
with col2:
btmvis_probs = biterm_bar(extype)
st.altair_chart(btmvis_probs, use_container_width=True)
#===download results===#
resultcsv = top_topics.to_csv().encode("utf-8")
st.download_button(label = "Download Results", data=resultcsv, file_name="results.csv", mime="text\csv", on_click="ignore")
except ValueError as g:
st.error('๐โโ๏ธ Please raise the number of topics and click submit')
except NameError as f:
st.warning('๐ฑ๏ธ Please click Submit')
with tab2:
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')
with tab3:
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')
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')
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')
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')
with tab4:
st.subheader(':blue[Biterm]', anchor=False)
st.text("Click the three dots at the top right then select the desired format.")
st.markdown("")
st.divider()
st.subheader(':blue[Downloading CSV Results]', anchor=False)
st.button("Download Results")
st.text("Click Download results button at bottom of page")
#===BERTopic===
elif method == 'BERTopic':
@st.cache_resource(ttl = 3600, show_spinner=False)
#@st.cache_data(ttl=3600, show_spinner=False)
def bertopic_vis(extype):
umap_model = UMAP(n_neighbors=bert_n_neighbors, n_components=bert_n_components,
min_dist=0.0, metric='cosine', random_state=bert_random_state)
cluster_model = KMeans(n_clusters=num_topic)
if bert_embedding_model == 'all-MiniLM-L6-v2':
model = SentenceTransformer('all-MiniLM-L6-v2')
lang = 'en'
embeddings = model.encode(topic_abs, show_progress_bar=True)
elif bert_embedding_model == 'en_core_web_sm':
nlp = en_core_web_sm.load(exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
model = nlp
lang = 'en'
embeddings = np.array([nlp(text).vector for text in topic_abs])
elif bert_embedding_model == 'paraphrase-multilingual-MiniLM-L12-v2':
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
lang = 'multilingual'
embeddings = model.encode(topic_abs, show_progress_bar=True)
representation_model = ""
if fine_tuning:
keybert = KeyBERTInspired()
mmr = MaximalMarginalRelevance(diversity=0.3)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
}
if topic_labelling:
if llm_provider == "OpenAI/gpt-4o":
client = openai.OpenAI(api_key=api_key)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
"test": OpenAI(client, model = "gpt-4o-mini", delay_in_seconds=10)
}
elif llm_provider == "Google/flan-t5":
pipe = pipeline("text2text-generation", model = "google/flan-t5-base")
clientmod = TextGeneration(pipe)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
"test": clientmod
}
elif llm_provider == "LiquidAI/LFM2-350M":
pipe = pipeline("text-generation", model = "LiquidAI/LFM2-350M")
clientmod = TextGeneration(pipe)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
"test": clientmod
}
vectorizer_model = CountVectorizer(ngram_range=(1, xgram), stop_words='english')
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)
topics, probs = topic_model.fit_transform(topic_abs, embeddings=embeddings)
if(fine_tuning and topic_labelling):
generated_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["test"].values()]
topic_model.set_topic_labels(generated_labels)
return topic_model, topics, probs, embeddings
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Topics(extype):
fig1 = topic_model.visualize_topics()
return fig1
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Documents(extype):
fig2 = topic_model.visualize_document_datamap(topic_abs, embeddings=embeddings, custom_labels = True)
return fig2
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Hierarchy(extype):
fig3 = topic_model.visualize_hierarchy(top_n_topics=num_topic, custom_labels = True)
return fig3
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Heatmap(extype):
global topic_model
fig4 = topic_model.visualize_heatmap(n_clusters=num_topic-1, width=1000, height=1000, custom_labels = True)
return fig4
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Barchart(extype):
fig5 = topic_model.visualize_barchart(top_n_topics=num_topic, custom_labels = True)
return fig5
tab1, tab2, tab3, tab4 = st.tabs(["๐ Generate visualization", "๐ Reference", "๐ Recommended Reading", "โฌ๏ธ Download Help"])
with tab1:
try:
with st.spinner('Performing computations. Please wait ...'):
topic_model, topics, probs, embeddings = bertopic_vis(extype)
time.sleep(.5)
st.toast('Visualize Topics', icon='๐')
fig1 = Vis_Topics(extype)
time.sleep(.5)
st.toast('Visualize Document', icon='๐')
fig2 = Vis_Documents(extype)
time.sleep(.5)
st.toast('Visualize Document Hierarchy', icon='๐')
fig3 = Vis_Hierarchy(extype)
time.sleep(.5)
st.toast('Visualize Topic Similarity', icon='๐')
fig4 = Vis_Heatmap(extype)
time.sleep(.5)
st.toast('Visualize Terms', icon='๐')
fig5 = Vis_Barchart(extype)
bertab1, bertab2, bertab3, bertab4, bertab5 = st.tabs(["Visualize Topics", "Visualize Terms", "Visualize Documents",
"Visualize Document Hierarchy", "Visualize Topic Similarity"])
with bertab1:
st.plotly_chart(fig1, use_container_width=True)
with bertab2:
st.plotly_chart(fig5, use_container_width=True)
with bertab3:
st.plotly_chart(fig2, use_container_width=True)
with bertab4:
st.plotly_chart(fig3, use_container_width=True)
with bertab5:
st.plotly_chart(fig4, use_container_width=True)
#===download results===#
results = topic_model.get_topic_info()
resultf = pd.DataFrame(results)
resultcsv = resultf.to_csv().encode("utf-8")
st.download_button(
label = "Download Results",
data=resultcsv,
file_name="results.csv",
mime="text\csv",
on_click="ignore",
)
except ValueError as e:
st.write(e)
st.error('๐โโ๏ธ Please raise the number of topics and click submit')
except NameError as e:
st.warning('๐ฑ๏ธ Please click Submit')
st.write(e)
with tab2:
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')
with tab3:
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')
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')
with tab4:
st.divider()
st.subheader(':blue[BERTopic]', anchor=False)
st.text("Click the camera icon on the top right menu")
st.markdown("")
st.divider()
st.subheader(':blue[Downloading CSV Results]', anchor=False)
st.button("Download Results")
st.text("Click Download results button at bottom of page")
except:
st.error("Please ensure that your file is correct. Please contact us if you find that this is an error.", icon="๐จ")
st.stop()
=======
#import module
import streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import numpy as np
import re
import string
import nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
nltk.download('stopwords')
from nltk.corpus import stopwords
import gensim
import gensim.corpora as corpora
from gensim.corpora import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from pprint import pprint
import pickle
import pyLDAvis
import pyLDAvis.gensim_models as gensimvis
from io import StringIO
from ipywidgets.embed import embed_minimal_html
from nltk.stem.snowball import SnowballStemmer
from bertopic import BERTopic
from bertopic.representation import KeyBERTInspired, MaximalMarginalRelevance, OpenAI, TextGeneration
import plotly.express as px
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import CountVectorizer
import bitermplus as btm
import tmplot as tmp
import tomotopy
import sys
import spacy
import en_core_web_sm
import pipeline
from html2image import Html2Image
from umap import UMAP
import os
import time
import json
from tools import sourceformat as sf
import datamapplot
from sentence_transformers import SentenceTransformer
import openai
from transformers import pipeline
#===config===
st.set_page_config(
page_title="Coconut",
page_icon="๐ฅฅ",
layout="wide",
initial_sidebar_state="collapsed"
)
hide_streamlit_style = """
<style>
#MainMenu
{visibility: hidden;}
footer {visibility: hidden;}
[data-testid="collapsedControl"] {display: none}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
with st.popover("๐ Menu"):
st.page_link("https://www.coconut-libtool.com/", label="Home", icon="๐ ")
st.page_link("pages/1 Scattertext.py", label="Scattertext", icon="1๏ธโฃ")
st.page_link("pages/2 Topic Modeling.py", label="Topic Modeling", icon="2๏ธโฃ")
st.page_link("pages/3 Bidirected Network.py", label="Bidirected Network", icon="3๏ธโฃ")
st.page_link("pages/4 Sunburst.py", label="Sunburst", icon="4๏ธโฃ")
st.page_link("pages/5 Burst Detection.py", label="Burst Detection", icon="5๏ธโฃ")
st.page_link("pages/6 Keywords Stem.py", label="Keywords Stem", icon="6๏ธโฃ")
st.page_link("pages/7 Sentiment Analysis.py", label="Sentiment Analysis", icon="7๏ธโฃ")
st.page_link("pages/8 Shifterator.py", label="Shifterator", icon="8๏ธโฃ")
st.page_link("pages/9 Summarization.py", label = "Summarization",icon ="9๏ธโฃ")
st.page_link("pages/10 WordCloud.py", label = "WordCloud", icon = "๐")
st.header("Topic Modeling", anchor=False)
st.subheader('Put your file here...', anchor=False)
#========unique id========
@st.cache_resource(ttl=3600)
def create_list():
l = [1, 2, 3]
return l
l = create_list()
first_list_value = l[0]
l[0] = first_list_value + 1
uID = str(l[0])
@st.cache_data(ttl=3600)
def get_ext(uploaded_file):
extype = uID+uploaded_file.name
return extype
#===clear cache===
def reset_biterm():
try:
biterm_map.clear()
biterm_bar.clear()
except NameError:
biterm_topic.clear()
def reset_all():
st.cache_data.clear()
#===avoiding deadlock===
os.environ["TOKENIZERS_PARALLELISM"] = "false"
#===upload file===
@st.cache_data(ttl=3600)
def upload(file):
papers = pd.read_csv(uploaded_file)
if "About the data" in papers.columns[0]:
papers = sf.dim(papers)
col_dict = {'MeSH terms': 'Keywords',
'PubYear': 'Year',
'Times cited': 'Cited by',
'Publication Type': 'Document Type'
}
papers.rename(columns=col_dict, inplace=True)
return papers
@st.cache_data(ttl=3600)
def conv_txt(extype):
if("PMID" in (uploaded_file.read()).decode()):
uploaded_file.seek(0)
papers = sf.medline(uploaded_file)
print(papers)
return papers
col_dict = {'TI': 'Title',
'SO': 'Source title',
'DE': 'Author Keywords',
'DT': 'Document Type',
'AB': 'Abstract',
'TC': 'Cited by',
'PY': 'Year',
'ID': 'Keywords Plus',
'rights_date_used': 'Year'}
uploaded_file.seek(0)
papers = pd.read_csv(uploaded_file, sep='\t')
if("htid" in papers.columns):
papers = sf.htrc(papers)
papers.rename(columns=col_dict, inplace=True)
print(papers)
return papers
@st.cache_data(ttl=3600)
def conv_json(extype):
col_dict={'title': 'title',
'rights_date_used': 'Year',
}
data = json.load(uploaded_file)
hathifile = data['gathers']
keywords = pd.DataFrame.from_records(hathifile)
keywords = sf.htrc(keywords)
keywords.rename(columns=col_dict,inplace=True)
return keywords
@st.cache_resource(ttl=3600)
def conv_pub(extype):
if (get_ext(extype)).endswith('.tar.gz'):
bytedata = extype.read()
keywords = sf.readPub(bytedata)
elif (get_ext(extype)).endswith('.xml'):
bytedata = extype.read()
keywords = sf.readxml(bytedata)
return keywords
#===Read data===
uploaded_file = st.file_uploader('', type=['csv', 'txt','json','tar.gz','xml'], on_change=reset_all)
if uploaded_file is not None:
try:
extype = get_ext(uploaded_file)
if extype.endswith('.csv'):
papers = upload(extype)
elif extype.endswith('.txt'):
papers = conv_txt(extype)
elif extype.endswith('.json'):
papers = conv_json(extype)
elif extype.endswith('.tar.gz') or extype.endswith('.xml'):
papers = conv_pub(uploaded_file)
coldf = sorted(papers.select_dtypes(include=['object']).columns.tolist())
c1, c2, c3 = st.columns([3,3,4])
method = c1.selectbox(
'Choose method',
('Choose...', 'pyLDA', 'Biterm', 'BERTopic'))
ColCho = c2.selectbox('Choose column', (["Abstract","Title", "Abstract + Title"]))
num_cho = c3.number_input('Choose number of topics', min_value=2, max_value=30, value=5)
d1, d2 = st.columns([3,7])
xgram = d1.selectbox("N-grams", ("1", "2", "3"))
xgram = int(xgram)
words_to_remove = d2.text_input("Remove specific words. Separate words by semicolons (;)")
rem_copyright = d1.toggle('Remove copyright statement', value=True)
rem_punc = d2.toggle('Remove punctuation', value=True)
#===advance settings===
with st.expander("๐งฎ Show advance settings"):
t1, t2, t3 = st.columns([3,3,4])
if method == 'pyLDA':
py_random_state = t1.number_input('Random state', min_value=0, max_value=None, step=1)
py_chunksize = t2.number_input('Chunk size', value=100 , min_value=10, max_value=None, step=1)
opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
elif method == 'Biterm':
btm_seed = t1.number_input('Random state seed', value=100 , min_value=1, max_value=None, step=1)
btm_iterations = t2.number_input('Iterations number', value=20 , min_value=2, max_value=None, step=1)
opt_threshold = t3.number_input('Threshold', value=100 , min_value=1, max_value=None, step=1)
elif method == 'BERTopic':
u1, u2 = st.columns([5,5])
bert_top_n_words = u1.number_input('top_n_words', value=5 , min_value=5, max_value=25, step=1)
bert_random_state = u2.number_input('random_state', value=42 , min_value=1, max_value=None, step=1)
bert_n_components = u1.number_input('n_components', value=5 , min_value=1, max_value=None, step=1)
bert_n_neighbors = u2.number_input('n_neighbors', value=15 , min_value=1, max_value=None, step=1)
bert_embedding_model = st.radio(
"embedding_model",
["all-MiniLM-L6-v2", "paraphrase-multilingual-MiniLM-L12-v2", "en_core_web_sm"], index=0, horizontal=True)
fine_tuning = st.toggle("Use Fine-tuning")
if fine_tuning:
topic_labelling = st.toggle("Automatic topic labelling")
if topic_labelling:
llm_provider = st.selectbox("Model",["OpenAI/gpt-4o","Google/flan-t5","LiquidAI/LFM2-350M"])
if llm_provider == "OpenAI/gpt-4o":
api_key = st.text_input("API Key")
else:
st.write('Please choose your preferred method')
#===clean csv===
@st.cache_data(ttl=3600, show_spinner=False)
def clean_csv(extype):
if (ColCho=="Abstract + Title"):
papers["Abstract + Title"] = papers["Title"] + " " + papers["Abstract"]
st.write(papers["Abstract + Title"])
paper = papers.dropna(subset=[ColCho])
#===mapping===
paper['Abstract_pre'] = paper[ColCho].map(lambda x: x.lower())
if rem_punc:
paper['Abstract_pre'] = paper['Abstract_pre'].map(
lambda x: re.sub(f"[{re.escape(string.punctuation)}]", " ", x)
).map(lambda x: re.sub(r"\s+", " ", x).strip())
paper['Abstract_pre'] = paper['Abstract_pre'].str.replace('[\u2018\u2019\u201c\u201d]', '', regex=True)
if rem_copyright:
paper['Abstract_pre'] = paper['Abstract_pre'].map(lambda x: re.sub('ยฉ.*', '', x))
#===stopword removal===
stop = stopwords.words('english')
paper['Abstract_stop'] = paper['Abstract_pre'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
#===lemmatize===
lemmatizer = WordNetLemmatizer()
@st.cache_resource(ttl=3600)
def lemmatize_words(text):
words = text.split()
words = [lemmatizer.lemmatize(word) for word in words]
return ' '.join(words)
paper['Abstract_lem'] = paper['Abstract_stop'].apply(lemmatize_words)
words_rmv = [word.strip() for word in words_to_remove.split(";")]
remove_dict = {word: None for word in words_rmv}
@st.cache_resource(ttl=3600)
def remove_words(text):
words = text.split()
cleaned_words = [word for word in words if word not in remove_dict]
return ' '.join(cleaned_words)
paper['Abstract_lem'] = paper['Abstract_lem'].map(remove_words)
topic_abs = paper.Abstract_lem.values.tolist()
return topic_abs, paper
topic_abs, paper=clean_csv(extype)
if st.button("Submit", on_click=reset_all):
num_topic = num_cho
if method == 'BERTopic':
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="โน๏ธ")
#===topic===
if method == 'Choose...':
st.write('')
elif method == 'pyLDA':
tab1, tab2, tab3, tab4 = st.tabs(["๐ Generate visualization", "๐ Reference", "๐ Recommended Reading", "โฌ๏ธ Download Help"])
with tab1:
#===visualization===
@st.cache_data(ttl=3600, show_spinner=False)
def pylda(extype):
topic_abs_LDA = [t.split(' ') for t in topic_abs]
bigram = Phrases(topic_abs_LDA, min_count=xgram, threshold=opt_threshold)
trigram = Phrases(bigram[topic_abs_LDA], threshold=opt_threshold)
bigram_mod = Phraser(bigram)
trigram_mod = Phraser(trigram)
topic_abs_LDA = [trigram_mod[bigram_mod[doc]] for doc in topic_abs_LDA]
id2word = Dictionary(topic_abs_LDA)
corpus = [id2word.doc2bow(text) for text in topic_abs_LDA]
#===LDA===
lda_model = LdaModel(corpus=corpus,
id2word=id2word,
num_topics=num_topic,
random_state=py_random_state,
chunksize=py_chunksize,
alpha='auto',
per_word_topics=False)
pprint(lda_model.print_topics())
doc_lda = lda_model[corpus]
topics = lda_model.show_topics(num_words = 30,formatted=False)
#===visualization===
coherence_model_lda = CoherenceModel(model=lda_model, texts=topic_abs_LDA, dictionary=id2word, coherence='c_v')
coherence_lda = coherence_model_lda.get_coherence()
vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
py_lda_vis_html = pyLDAvis.prepared_data_to_html(vis)
return py_lda_vis_html, coherence_lda, vis, topics
with st.spinner('Performing computations. Please wait ...'):
try:
py_lda_vis_html, coherence_lda, vis, topics = pylda(extype)
st.write('Coherence score: ', coherence_lda)
components.html(py_lda_vis_html, width=1500, height=800)
st.markdown('Copyright (c) 2015, Ben Mabey. https://github.com/bmabey/pyLDAvis')
@st.cache_data(ttl=3600, show_spinner=False)
def img_lda(vis):
pyLDAvis.save_html(vis, 'output.html')
hti = Html2Image()
hti.browser.flags = ['--default-background-color=ffffff', '--hide-scrollbars']
hti.browser.use_new_headless = None
css = "body {background: white;}"
hti.screenshot(
other_file='output.html', css_str=css, size=(1500, 800),
save_as='ldavis_img.png'
)
img_lda(vis)
d1, d2 = st.columns(2)
with open("ldavis_img.png", "rb") as file:
btn = d1.download_button(
label="Download image",
data=file,
file_name="ldavis_img.png",
mime="image/png"
)
#===download results===#
resultf = pd.DataFrame(topics)
#formatting
resultf = resultf.transpose()
resultf = resultf.drop([0])
resultf = resultf.explode(list(range(len(resultf.columns))), ignore_index=False)
resultcsv = resultf.to_csv().encode("utf-8")
d2.download_button(
label = "Download Results",
data=resultcsv,
file_name="results.csv",
mime="text\csv",
on_click="ignore")
except NameError as f:
st.warning('๐ฑ๏ธ Please click Submit')
with tab2:
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')
with tab3:
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')
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')
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')
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')
with tab4:
st.subheader(':blue[pyLDA]', anchor=False)
st.button('Download image')
st.text("Click Download Image button.")
st.divider()
st.subheader(':blue[Downloading CSV Results]', anchor=False)
st.button("Download Results")
st.text("Click Download results button at bottom of page")
#===Biterm===
elif method == 'Biterm':
#===optimize Biterm===
@st.cache_data(ttl=3600, show_spinner=False)
def biterm_topic(extype):
tokenized_abs = [t.split(' ') for t in topic_abs]
bigram = Phrases(tokenized_abs, min_count=xgram, threshold=opt_threshold)
trigram = Phrases(bigram[tokenized_abs], threshold=opt_threshold)
bigram_mod = Phraser(bigram)
trigram_mod = Phraser(trigram)
topic_abs_ngram = [trigram_mod[bigram_mod[doc]] for doc in tokenized_abs]
topic_abs_str = [' '.join(doc) for doc in topic_abs_ngram]
X, vocabulary, vocab_dict = btm.get_words_freqs(topic_abs_str)
tf = np.array(X.sum(axis=0)).ravel()
docs_vec = btm.get_vectorized_docs(topic_abs, vocabulary)
docs_lens = list(map(len, docs_vec))
biterms = btm.get_biterms(docs_vec)
model = btm.BTM(X, vocabulary, seed=btm_seed, T=num_topic, M=20, alpha=50/8, beta=0.01)
model.fit(biterms, iterations=btm_iterations)
p_zd = model.transform(docs_vec)
coherence = model.coherence_
phi = tmp.get_phi(model)
topics_coords = tmp.prepare_coords(model)
totaltop = topics_coords.label.values.tolist()
perplexity = model.perplexity_
top_topics = model.df_words_topics_
return topics_coords, phi, totaltop, perplexity, top_topics
tab1, tab2, tab3, tab4 = st.tabs(["๐ Generate visualization", "๐ Reference", "๐ Recommended Reading", "โฌ๏ธ Download Help"])
with tab1:
try:
with st.spinner('Performing computations. Please wait ...'):
topics_coords, phi, totaltop, perplexity, top_topics = biterm_topic(extype)
col1, col2 = st.columns([4,6])
@st.cache_data(ttl=3600)
def biterm_map(extype):
btmvis_coords = tmp.plot_scatter_topics(topics_coords, size_col='size', label_col='label', topic=numvis)
return btmvis_coords
@st.cache_data(ttl=3600)
def biterm_bar(extype):
terms_probs = tmp.calc_terms_probs_ratio(phi, topic=numvis, lambda_=1)
btmvis_probs = tmp.plot_terms(terms_probs, font_size=12)
return btmvis_probs
with col1:
st.write('Perplexity score: ', perplexity)
st.write('')
numvis = st.selectbox(
'Choose topic',
(totaltop), on_change=reset_biterm)
btmvis_coords = biterm_map(extype)
st.altair_chart(btmvis_coords)
with col2:
btmvis_probs = biterm_bar(extype)
st.altair_chart(btmvis_probs, use_container_width=True)
#===download results===#
resultcsv = top_topics.to_csv().encode("utf-8")
st.download_button(label = "Download Results", data=resultcsv, file_name="results.csv", mime="text\csv", on_click="ignore")
except ValueError as g:
st.error('๐โโ๏ธ Please raise the number of topics and click submit')
except NameError as f:
st.warning('๐ฑ๏ธ Please click Submit')
with tab2:
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')
with tab3:
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')
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')
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')
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')
with tab4:
st.subheader(':blue[Biterm]', anchor=False)
st.text("Click the three dots at the top right then select the desired format.")
st.markdown("")
st.divider()
st.subheader(':blue[Downloading CSV Results]', anchor=False)
st.button("Download Results")
st.text("Click Download results button at bottom of page")
#===BERTopic===
elif method == 'BERTopic':
@st.cache_resource(ttl = 3600, show_spinner=False)
#@st.cache_data(ttl=3600, show_spinner=False)
def bertopic_vis(extype):
umap_model = UMAP(n_neighbors=bert_n_neighbors, n_components=bert_n_components,
min_dist=0.0, metric='cosine', random_state=bert_random_state)
cluster_model = KMeans(n_clusters=num_topic)
if bert_embedding_model == 'all-MiniLM-L6-v2':
model = SentenceTransformer('all-MiniLM-L6-v2')
lang = 'en'
embeddings = model.encode(topic_abs, show_progress_bar=True)
elif bert_embedding_model == 'en_core_web_sm':
nlp = en_core_web_sm.load(exclude=['tagger', 'parser', 'ner', 'attribute_ruler', 'lemmatizer'])
model = nlp
lang = 'en'
embeddings = np.array([nlp(text).vector for text in topic_abs])
elif bert_embedding_model == 'paraphrase-multilingual-MiniLM-L12-v2':
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
lang = 'multilingual'
embeddings = model.encode(topic_abs, show_progress_bar=True)
representation_model = ""
if fine_tuning:
keybert = KeyBERTInspired()
mmr = MaximalMarginalRelevance(diversity=0.3)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
}
if topic_labelling:
if llm_provider == "OpenAI/gpt-4o":
client = openai.OpenAI(api_key=api_key)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
"test": OpenAI(client, model = "gpt-4o-mini", delay_in_seconds=10)
}
elif llm_provider == "Google/flan-t5":
pipe = pipeline("text2text-generation", model = "google/flan-t5-base")
clientmod = TextGeneration(pipe)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
"test": clientmod
}
elif llm_provider == "LiquidAI/LFM2-350M":
pipe = pipeline("text-generation", model = "LiquidAI/LFM2-350M")
clientmod = TextGeneration(pipe)
representation_model = {
"KeyBERT": keybert,
"MMR": mmr,
"test": clientmod
}
vectorizer_model = CountVectorizer(ngram_range=(1, xgram), stop_words='english')
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)
topics, probs = topic_model.fit_transform(topic_abs, embeddings=embeddings)
if(fine_tuning and topic_labelling):
generated_labels = [label[0][0].split("\n")[0] for label in topic_model.get_topics(full=True)["test"].values()]
topic_model.set_topic_labels(generated_labels)
return topic_model, topics, probs, embeddings
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Topics(extype):
fig1 = topic_model.visualize_topics()
return fig1
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Documents(extype):
fig2 = topic_model.visualize_document_datamap(topic_abs, embeddings=embeddings, custom_labels = True)
return fig2
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Hierarchy(extype):
fig3 = topic_model.visualize_hierarchy(top_n_topics=num_topic, custom_labels = True)
return fig3
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Heatmap(extype):
global topic_model
fig4 = topic_model.visualize_heatmap(n_clusters=num_topic-1, width=1000, height=1000, custom_labels = True)
return fig4
@st.cache_resource(ttl = 3600, show_spinner=False)
def Vis_Barchart(extype):
fig5 = topic_model.visualize_barchart(top_n_topics=num_topic, custom_labels = True)
return fig5
tab1, tab2, tab3, tab4 = st.tabs(["๐ Generate visualization", "๐ Reference", "๐ Recommended Reading", "โฌ๏ธ Download Help"])
with tab1:
try:
with st.spinner('Performing computations. Please wait ...'):
topic_model, topics, probs, embeddings = bertopic_vis(extype)
time.sleep(.5)
st.toast('Visualize Topics', icon='๐')
fig1 = Vis_Topics(extype)
time.sleep(.5)
st.toast('Visualize Document', icon='๐')
fig2 = Vis_Documents(extype)
time.sleep(.5)
st.toast('Visualize Document Hierarchy', icon='๐')
fig3 = Vis_Hierarchy(extype)
time.sleep(.5)
st.toast('Visualize Topic Similarity', icon='๐')
fig4 = Vis_Heatmap(extype)
time.sleep(.5)
st.toast('Visualize Terms', icon='๐')
fig5 = Vis_Barchart(extype)
bertab1, bertab2, bertab3, bertab4, bertab5 = st.tabs(["Visualize Topics", "Visualize Terms", "Visualize Documents",
"Visualize Document Hierarchy", "Visualize Topic Similarity"])
with bertab1:
st.plotly_chart(fig1, use_container_width=True)
with bertab2:
st.plotly_chart(fig5, use_container_width=True)
with bertab3:
st.plotly_chart(fig2, use_container_width=True)
with bertab4:
st.plotly_chart(fig3, use_container_width=True)
with bertab5:
st.plotly_chart(fig4, use_container_width=True)
#===download results===#
results = topic_model.get_topic_info()
resultf = pd.DataFrame(results)
resultcsv = resultf.to_csv().encode("utf-8")
st.download_button(
label = "Download Results",
data=resultcsv,
file_name="results.csv",
mime="text\csv",
on_click="ignore",
)
except ValueError as e:
st.write(e)
st.error('๐โโ๏ธ Please raise the number of topics and click submit')
except NameError as e:
st.warning('๐ฑ๏ธ Please click Submit')
st.write(e)
with tab2:
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')
with tab3:
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')
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')
with tab4:
st.divider()
st.subheader(':blue[BERTopic]', anchor=False)
st.text("Click the camera icon on the top right menu")
st.markdown("")
st.divider()
st.subheader(':blue[Downloading CSV Results]', anchor=False)
st.button("Download Results")
st.text("Click Download results button at bottom of page")
except:
st.error("Please ensure that your file is correct. Please contact us if you find that this is an error.", icon="๐จ")
st.stop()
>>>>>>> e52d4a30c18f770eb968980667fa8e5a7b287580
|