Spaces:
Running
Running
first-commit
Browse files- .gitignore +2 -0
- .streamlit/config.toml +6 -0
- app.py +254 -0
- emotion_detection.py +74 -0
- keyword_extraction.py +158 -0
- named_entity_recognition.py +65 -0
- part_of_speech_tagging.py +26 -0
- requirements.txt +12 -0
- sentiment_analysis.py +84 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
.DS_Store
|
2 |
+
.idea/
|
.streamlit/config.toml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[theme]
|
2 |
+
primaryColor="#f58442"
|
3 |
+
backgroundColor="#FFFFFF"
|
4 |
+
secondaryBackgroundColor="#F0F2F6"
|
5 |
+
textColor="#262730"
|
6 |
+
font="sans serif"
|
app.py
ADDED
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import streamlit as st
|
3 |
+
from annotated_text import annotated_text
|
4 |
+
from streamlit_option_menu import option_menu
|
5 |
+
from sentiment_analysis import SentimentAnalysis
|
6 |
+
from keyword_extraction import KeywordExtractor
|
7 |
+
from part_of_speech_tagging import POSTagging
|
8 |
+
from emotion_detection import EmotionDetection
|
9 |
+
from named_entity_recognition import NamedEntityRecognition
|
10 |
+
|
11 |
+
hide_streamlit_style = """
|
12 |
+
<style>
|
13 |
+
#MainMenu {visibility: hidden;}
|
14 |
+
footer {visibility: hidden;}
|
15 |
+
</style>
|
16 |
+
"""
|
17 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
18 |
+
|
19 |
+
|
20 |
+
@st.cache(allow_output_mutation=True)
|
21 |
+
def load_sentiment_model():
|
22 |
+
return SentimentAnalysis()
|
23 |
+
|
24 |
+
@st.cache(allow_output_mutation=True)
|
25 |
+
def load_keyword_model():
|
26 |
+
return KeywordExtractor()
|
27 |
+
|
28 |
+
@st.cache(allow_output_mutation=True)
|
29 |
+
def load_pos_model():
|
30 |
+
return POSTagging()
|
31 |
+
|
32 |
+
@st.cache(allow_output_mutation=True)
|
33 |
+
def load_emotion_model():
|
34 |
+
return EmotionDetection()
|
35 |
+
|
36 |
+
@st.cache(allow_output_mutation=True)
|
37 |
+
def load_ner_model():
|
38 |
+
return NamedEntityRecognition()
|
39 |
+
|
40 |
+
|
41 |
+
sentiment_analyzer = load_sentiment_model()
|
42 |
+
keyword_extractor = load_keyword_model()
|
43 |
+
pos_tagger = load_pos_model()
|
44 |
+
emotion_detector = load_emotion_model()
|
45 |
+
ner = load_ner_model()
|
46 |
+
|
47 |
+
example_text = "This is example text that contains both names of organizations like Hugging Face and cities like New York, all while portraying an upbeat attitude."
|
48 |
+
|
49 |
+
with st.sidebar:
|
50 |
+
page = option_menu(menu_title='Menu',
|
51 |
+
menu_icon="robot",
|
52 |
+
options=["Welcome!",
|
53 |
+
"Sentiment Analysis",
|
54 |
+
"Keyword Extraction",
|
55 |
+
"Part of Speech Tagging",
|
56 |
+
"Emotion Detection",
|
57 |
+
"Named Entity Recognition"],
|
58 |
+
icons=["house-door",
|
59 |
+
"chat-dots",
|
60 |
+
"key",
|
61 |
+
"tag",
|
62 |
+
"emoji-heart-eyes",
|
63 |
+
"building"],
|
64 |
+
default_index=0
|
65 |
+
)
|
66 |
+
|
67 |
+
st.title('Open-source NLP')
|
68 |
+
|
69 |
+
if page == "Welcome!":
|
70 |
+
st.header('Welcome!')
|
71 |
+
|
72 |
+
st.markdown("")
|
73 |
+
st.write(
|
74 |
+
"""
|
75 |
+
|
76 |
+
|
77 |
+
"""
|
78 |
+
)
|
79 |
+
|
80 |
+
st.subheader("Quickstart")
|
81 |
+
st.write(
|
82 |
+
"""
|
83 |
+
Replace the example text below and flip through the pages in the menu to perform NLP tasks on-demand!
|
84 |
+
Feel free to use the example text for a test run.
|
85 |
+
"""
|
86 |
+
)
|
87 |
+
|
88 |
+
text = st.text_area("Paste text here", value=example_text)
|
89 |
+
|
90 |
+
st.subheader("Introduction")
|
91 |
+
st.write("""
|
92 |
+
Hello! This application is a celebration of open-source and the power that programmers have been granted today
|
93 |
+
by those who give back to the community. This tool was constructed using Streamlit, Huggingface Transformers,
|
94 |
+
Transformers-Interpret, NLTK, Spacy, amongst other open-source Python libraries and models.
|
95 |
+
|
96 |
+
Utilizing this tool you will be able to perform a multitude of Natural Language Processing Tasks on a range of
|
97 |
+
different tasks. All you need to do is paste your input, select your task, and hit the start button!
|
98 |
+
|
99 |
+
* This application currently supports:
|
100 |
+
* Sentiment Analysis
|
101 |
+
* Keyword Extraction
|
102 |
+
* Part of Speech Tagging
|
103 |
+
* Emotion Detection
|
104 |
+
* Named Entity Recognition
|
105 |
+
|
106 |
+
More features may be added in the future including article/tweet/youtube input, improved text annotation, model quality improvements,
|
107 |
+
depending on community feedback. Please reach out to me at [email protected] or at my Linkedin page listed
|
108 |
+
below if you have ideas or suggestions for improvement.
|
109 |
+
|
110 |
+
If you would like to contribute yourself, feel free to fork the Github repository listed below and submit a merge request.
|
111 |
+
"""
|
112 |
+
)
|
113 |
+
st.subheader("Notes")
|
114 |
+
st.write(
|
115 |
+
"""
|
116 |
+
* This dashboard was constructed by myself, but every resource used is open-source! If you are interested in my other works you can view them here:
|
117 |
+
|
118 |
+
[Project Github](https://github.com/MiesnerJacob/Multi-task-NLP-dashboard)
|
119 |
+
|
120 |
+
[Jacob Miesner's Github](https://github.com/MiesnerJacob)
|
121 |
+
|
122 |
+
[Jacob Miesner's Linkedin](https://www.linkedin.com/in/jacob-miesner-885050125/)
|
123 |
+
|
124 |
+
[Jacob Miesner's Website](https://www.jacobmiesner.com)
|
125 |
+
|
126 |
+
* The prediction justification for some of the tasks are printed as the model views them. For this reason the text may contain special tokens like [CLS] or [SEP] or even hashtags splitting words. If you are are familiar with language models you will recognize these, if you do not have prior experience with language models you can ignore these characters.
|
127 |
+
"""
|
128 |
+
)
|
129 |
+
|
130 |
+
elif page == "Sentiment Analysis":
|
131 |
+
st.header('Sentiment Analysis')
|
132 |
+
st.markdown("")
|
133 |
+
st.write(
|
134 |
+
"""
|
135 |
+
|
136 |
+
|
137 |
+
"""
|
138 |
+
)
|
139 |
+
|
140 |
+
text = st.text_area("Paste text here", value=example_text)
|
141 |
+
|
142 |
+
if st.button('🔥 Run!'):
|
143 |
+
with st.spinner("Loading..."):
|
144 |
+
preds, html = sentiment_analyzer.run(text)
|
145 |
+
st.success('All done!')
|
146 |
+
st.write("")
|
147 |
+
st.subheader("Sentiment Predictions")
|
148 |
+
st.bar_chart(data=preds, width=0, height=0, use_container_width=True)
|
149 |
+
st.write("")
|
150 |
+
st.subheader("Sentiment Justification")
|
151 |
+
raw_html = html._repr_html_()
|
152 |
+
st.components.v1.html(raw_html, height=500)
|
153 |
+
|
154 |
+
elif page == "Keyword Extraction":
|
155 |
+
st.header('Keyword Extraction')
|
156 |
+
st.markdown("")
|
157 |
+
st.write(
|
158 |
+
"""
|
159 |
+
|
160 |
+
|
161 |
+
"""
|
162 |
+
)
|
163 |
+
|
164 |
+
text = st.text_area("Paste text here", value=example_text)
|
165 |
+
|
166 |
+
max_keywords = st.slider('# of Keywords Max Limit', min_value=1, max_value=10, value=5, step=1)
|
167 |
+
|
168 |
+
if st.button('🔥 Run!'):
|
169 |
+
with st.spinner("Loading..."):
|
170 |
+
annotation, keywords = keyword_extractor.generate(text, max_keywords)
|
171 |
+
st.success('All done!')
|
172 |
+
|
173 |
+
if annotation:
|
174 |
+
st.subheader("Keyword Annotation")
|
175 |
+
st.write("")
|
176 |
+
annotated_text(*annotation)
|
177 |
+
st.text("")
|
178 |
+
|
179 |
+
st.subheader("Extracted Keywords")
|
180 |
+
st.write("")
|
181 |
+
df = pd.DataFrame(keywords, columns=['Extracted Keywords'])
|
182 |
+
csv = df.to_csv(index=False).encode('utf-8')
|
183 |
+
st.download_button('Download Keywords to CSV', csv, file_name='news_intelligence_keywords.csv')
|
184 |
+
|
185 |
+
data_table = st.table(df)
|
186 |
+
|
187 |
+
elif page == "Part of Speech Tagging":
|
188 |
+
st.header('Part of Speech Tagging')
|
189 |
+
st.markdown("")
|
190 |
+
st.write(
|
191 |
+
"""
|
192 |
+
|
193 |
+
|
194 |
+
"""
|
195 |
+
)
|
196 |
+
|
197 |
+
text = st.text_area("Paste text here", value=example_text)
|
198 |
+
|
199 |
+
if st.button('🔥 Run!'):
|
200 |
+
with st.spinner("Loading..."):
|
201 |
+
preds = pos_tagger.classify(text)
|
202 |
+
st.success('All done!')
|
203 |
+
st.write("")
|
204 |
+
st.subheader("Part of Speech tags")
|
205 |
+
annotated_text(*preds)
|
206 |
+
st.write("")
|
207 |
+
st.components.v1.iframe('https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html', height=1000)
|
208 |
+
|
209 |
+
elif page == "Emotion Detection":
|
210 |
+
st.header('Emotion Detection')
|
211 |
+
st.markdown("")
|
212 |
+
st.write(
|
213 |
+
"""
|
214 |
+
|
215 |
+
|
216 |
+
"""
|
217 |
+
)
|
218 |
+
|
219 |
+
text = st.text_area("Paste text here", value=example_text)
|
220 |
+
|
221 |
+
if st.button('🔥 Run!'):
|
222 |
+
with st.spinner("Loading..."):
|
223 |
+
preds, html = emotion_detector.run(text)
|
224 |
+
st.success('All done!')
|
225 |
+
st.write("")
|
226 |
+
st.subheader("Emotion Predictions")
|
227 |
+
st.bar_chart(data=preds, width=0, height=0, use_container_width=True)
|
228 |
+
raw_html = html._repr_html_()
|
229 |
+
st.write("")
|
230 |
+
st.subheader("Emotion Justification")
|
231 |
+
st.components.v1.html(raw_html, height=500)
|
232 |
+
|
233 |
+
elif page == "Named Entity Recognition":
|
234 |
+
st.header('Named Entity Recognition')
|
235 |
+
st.markdown("")
|
236 |
+
st.write(
|
237 |
+
"""
|
238 |
+
|
239 |
+
|
240 |
+
"""
|
241 |
+
)
|
242 |
+
|
243 |
+
text = st.text_area("Paste text here", value=example_text)
|
244 |
+
|
245 |
+
if st.button('🔥 Run!'):
|
246 |
+
with st.spinner("Loading..."):
|
247 |
+
preds, ner_annotation = ner.classify(text)
|
248 |
+
st.success('All done!')
|
249 |
+
st.write("")
|
250 |
+
st.subheader("NER Predictions")
|
251 |
+
annotated_text(*ner_annotation)
|
252 |
+
st.write("")
|
253 |
+
st.subheader("NER Prediction Metadata")
|
254 |
+
st.write(preds)
|
emotion_detection.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
+
from transformers_interpret import SequenceClassificationExplainer
|
3 |
+
import torch
|
4 |
+
import pandas as pd
|
5 |
+
|
6 |
+
|
7 |
+
class EmotionDetection:
|
8 |
+
"""
|
9 |
+
Emotion Detection on text data.
|
10 |
+
|
11 |
+
Attributes:
|
12 |
+
tokenizer: An instance of Hugging Face Tokenizer
|
13 |
+
model: An instance of Hugging Face Model
|
14 |
+
explainer: An instance of SequenceClassificationExplainer from Transformers interpret
|
15 |
+
"""
|
16 |
+
|
17 |
+
def __init__(self):
|
18 |
+
hub_location = 'cardiffnlp/twitter-roberta-base-emotion'
|
19 |
+
self.tokenizer = AutoTokenizer.from_pretrained(hub_location)
|
20 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(hub_location)
|
21 |
+
self.explainer = SequenceClassificationExplainer(self.model, self.tokenizer)
|
22 |
+
|
23 |
+
def justify(self, text):
|
24 |
+
"""
|
25 |
+
Get html annotation for displaying emotion justification over text.
|
26 |
+
|
27 |
+
Parameters:
|
28 |
+
text (str): The user input string to emotion justification
|
29 |
+
|
30 |
+
Returns:
|
31 |
+
html (hmtl): html object for plotting emotion prediction justification
|
32 |
+
"""
|
33 |
+
|
34 |
+
word_attributions = self.explainer(text)
|
35 |
+
html = self.explainer.visualize("example.html")
|
36 |
+
|
37 |
+
return html
|
38 |
+
|
39 |
+
def classify(self, text):
|
40 |
+
"""
|
41 |
+
Recognize Emotion in text.
|
42 |
+
|
43 |
+
Parameters:
|
44 |
+
text (str): The user input string to perform emotion classification on
|
45 |
+
|
46 |
+
Returns:
|
47 |
+
predictions (str): The predicted probabilities for emotion classes
|
48 |
+
"""
|
49 |
+
|
50 |
+
tokens = self.tokenizer.encode_plus(text, add_special_tokens=False, return_tensors='pt')
|
51 |
+
outputs = self.model(**tokens)
|
52 |
+
probs = torch.nn.functional.softmax(outputs[0], dim=-1)
|
53 |
+
probs = probs.mean(dim=0).detach().numpy()
|
54 |
+
labels = list(self.model.config.id2label.values())
|
55 |
+
preds = pd.Series(probs, index=labels, name='Predicted Probability')
|
56 |
+
|
57 |
+
return preds
|
58 |
+
|
59 |
+
def run(self, text):
|
60 |
+
"""
|
61 |
+
Classify and Justify Emotion in text.
|
62 |
+
|
63 |
+
Parameters:
|
64 |
+
text (str): The user input string to perform emotion classification on
|
65 |
+
|
66 |
+
Returns:
|
67 |
+
predictions (str): The predicted probabilities for emotion classes
|
68 |
+
html (hmtl): html object for plotting emotion prediction justification
|
69 |
+
"""
|
70 |
+
|
71 |
+
preds = self.classify(text)
|
72 |
+
html = self.justify(text)
|
73 |
+
|
74 |
+
return preds, html
|
keyword_extraction.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import nltk
|
2 |
+
import pytextrank
|
3 |
+
import re
|
4 |
+
from operator import itemgetter
|
5 |
+
import en_core_web_sm
|
6 |
+
|
7 |
+
|
8 |
+
class KeywordExtractor:
|
9 |
+
"""
|
10 |
+
Keyword Extraction on text data
|
11 |
+
|
12 |
+
Attributes:
|
13 |
+
nlp: An instance English pipeline optimized for CPU for spacy
|
14 |
+
"""
|
15 |
+
|
16 |
+
def __init__(self):
|
17 |
+
self.nlp = en_core_web_sm.load()
|
18 |
+
self.nlp.add_pipe("textrank")
|
19 |
+
|
20 |
+
def get_keywords(self, text, max_keywords):
|
21 |
+
"""
|
22 |
+
Extract keywords from text.
|
23 |
+
|
24 |
+
Parameters:
|
25 |
+
text (str): The user input string to extract keywords from
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
kws (list): list of extracted keywords
|
29 |
+
"""
|
30 |
+
|
31 |
+
doc = self.nlp(text)
|
32 |
+
|
33 |
+
kws = [i.text for i in doc._.phrases[:max_keywords]]
|
34 |
+
|
35 |
+
return kws
|
36 |
+
|
37 |
+
def get_keyword_indices(self, kws, text):
|
38 |
+
"""
|
39 |
+
Extract keywords from text.
|
40 |
+
|
41 |
+
Parameters:
|
42 |
+
kws (list): list of extracted keywords
|
43 |
+
text (str): The user input string to extract keywords from
|
44 |
+
|
45 |
+
Returns:
|
46 |
+
keyword_indices (list): list of indices for keyword boundaries in text
|
47 |
+
"""
|
48 |
+
|
49 |
+
keyword_indices = []
|
50 |
+
for s in kws:
|
51 |
+
indices = [[m.start(), m.end()] for m in re.finditer(re.escape(s), text)]
|
52 |
+
keyword_indices.extend(indices)
|
53 |
+
|
54 |
+
return keyword_indices
|
55 |
+
|
56 |
+
def merge_overlapping_indices(self, keyword_indices):
|
57 |
+
"""
|
58 |
+
Merge overlapping keyword indices.
|
59 |
+
|
60 |
+
Parameters:
|
61 |
+
keyword_indices (list): list of indices for keyword boundaries in text
|
62 |
+
|
63 |
+
Returns:
|
64 |
+
keyword_indices (list): list of indices for keyword boundaries in with overlapping combined
|
65 |
+
"""
|
66 |
+
|
67 |
+
# Sort the array on the basis of start values of intervals.
|
68 |
+
keyword_indices.sort()
|
69 |
+
|
70 |
+
stack = []
|
71 |
+
# insert first interval into stack
|
72 |
+
stack.append(keyword_indices[0])
|
73 |
+
for i in keyword_indices[1:]:
|
74 |
+
# Check for overlapping interval,
|
75 |
+
# if interval overlap
|
76 |
+
if (stack[-1][0] <= i[0] <= stack[-1][-1]) or (stack[-1][-1] == i[0]-1):
|
77 |
+
stack[-1][-1] = max(stack[-1][-1], i[-1])
|
78 |
+
else:
|
79 |
+
stack.append(i)
|
80 |
+
return stack
|
81 |
+
|
82 |
+
def merge_until_finished(self, keyword_indices):
|
83 |
+
"""
|
84 |
+
Loop until no overlapping keyword indices left.
|
85 |
+
|
86 |
+
Parameters:
|
87 |
+
keyword_indices (list): list of indices for keyword boundaries in text
|
88 |
+
|
89 |
+
Returns:
|
90 |
+
keyword_indices (list): list of indices for keyword boundaries in with overlapping combined
|
91 |
+
"""
|
92 |
+
|
93 |
+
len_indices = 0
|
94 |
+
while True:
|
95 |
+
# Merge overlapping indices
|
96 |
+
merged = self.merge_overlapping_indices(keyword_indices)
|
97 |
+
# Check to see if merging reduced number of annotation indices
|
98 |
+
# If merging did not reduce list return final indicies
|
99 |
+
if len_indices == len(merged):
|
100 |
+
out_indices = sorted(merged, key=itemgetter(0))
|
101 |
+
return out_indices
|
102 |
+
else:
|
103 |
+
len_indices = len(merged)
|
104 |
+
|
105 |
+
def get_annotation(self, text, keyword_indices):
|
106 |
+
"""
|
107 |
+
Create text annotation for extracted keywords.
|
108 |
+
|
109 |
+
Parameters:
|
110 |
+
keyword_indices (list): list of indices for keyword boundaries in text
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
annotation (list): list of tuples for generating html
|
114 |
+
"""
|
115 |
+
|
116 |
+
# Turn list to numpy array
|
117 |
+
arr = list(text)
|
118 |
+
|
119 |
+
# Loop through indices in list and insert delimeters
|
120 |
+
for idx in sorted(keyword_indices, reverse=True):
|
121 |
+
arr.insert(idx[0], "<kw>")
|
122 |
+
arr.insert(idx[1]+1, "<!kw> <kw>")
|
123 |
+
|
124 |
+
# join array
|
125 |
+
joined_annotation = ''.join(arr)
|
126 |
+
|
127 |
+
# split array on delimeter
|
128 |
+
split = joined_annotation.split('<kw>')
|
129 |
+
|
130 |
+
# Create annotation for keywords in text
|
131 |
+
annotation = [(x.replace('<!kw> ', ''), "KEY", "#26aaef") if "<!kw>" in x else x for x in split]
|
132 |
+
|
133 |
+
return annotation
|
134 |
+
|
135 |
+
def generate(self, text, max_keywords):
|
136 |
+
"""
|
137 |
+
Create text annotation for extracted keywords.
|
138 |
+
|
139 |
+
Parameters:
|
140 |
+
text (str): The user input string to extract keywords from
|
141 |
+
max_keywords (int): Limit on number of keywords to generate
|
142 |
+
|
143 |
+
Returns:
|
144 |
+
annotation (list): list of tuples for generating html
|
145 |
+
kws (list): list of extracted keywords
|
146 |
+
"""
|
147 |
+
|
148 |
+
kws = self.get_keywords(text, max_keywords)
|
149 |
+
|
150 |
+
indices = list(self.get_keyword_indices(kws, text))
|
151 |
+
if indices:
|
152 |
+
indices_merged = self.merge_until_finished(indices)
|
153 |
+
annotation = self.get_annotation(text, indices_merged)
|
154 |
+
else:
|
155 |
+
annotation = None
|
156 |
+
|
157 |
+
return annotation, kws
|
158 |
+
|
named_entity_recognition.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForTokenClassification
|
2 |
+
from transformers import pipeline
|
3 |
+
|
4 |
+
|
5 |
+
class NamedEntityRecognition:
|
6 |
+
"""
|
7 |
+
Named Entity Recognition on text data.
|
8 |
+
|
9 |
+
Attributes:
|
10 |
+
tokenizer: An instance of Hugging Face Tokenizer
|
11 |
+
model: An instance of Hugging Face Model
|
12 |
+
nlp: An instance of Hugging Face Named Entity Recognition pipeline
|
13 |
+
"""
|
14 |
+
|
15 |
+
def __init__(self):
|
16 |
+
tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-large-finetuned-conll03-english")
|
17 |
+
model = AutoModelForTokenClassification.from_pretrained("xlm-roberta-large-finetuned-conll03-english")
|
18 |
+
self.nlp = pipeline("ner", model=model, tokenizer=tokenizer, grouped_entities=True)
|
19 |
+
|
20 |
+
def get_annotation(self, preds, text):
|
21 |
+
"""
|
22 |
+
Get html annotation for displaying entities over text.
|
23 |
+
|
24 |
+
Parameters:
|
25 |
+
preds (dict): List of entities and their associated metadata
|
26 |
+
text (str): The user input string to generate entity tags for
|
27 |
+
|
28 |
+
Returns:
|
29 |
+
final_annotation (list): List of tuples to pass to text annotation html creator
|
30 |
+
"""
|
31 |
+
|
32 |
+
splits = [0]
|
33 |
+
entities = {}
|
34 |
+
for i in preds:
|
35 |
+
splits.append(i['start'])
|
36 |
+
splits.append(i['end'])
|
37 |
+
entities[i['word']] = i['entity_group']
|
38 |
+
|
39 |
+
# Exclude bad preds
|
40 |
+
exclude = ['', '.', '. ', ' ']
|
41 |
+
for x in exclude:
|
42 |
+
if x in entities.keys():
|
43 |
+
entities.pop(x)
|
44 |
+
|
45 |
+
parts = [text[i:j] for i, j in zip(splits, splits[1:] + [None])]
|
46 |
+
|
47 |
+
final_annotation = [(x, entities[x], "") if x in entities.keys() else x for x in parts]
|
48 |
+
|
49 |
+
return final_annotation
|
50 |
+
|
51 |
+
def classify(self, text):
|
52 |
+
"""
|
53 |
+
Recognize Named Entities in text.
|
54 |
+
|
55 |
+
Parameters:
|
56 |
+
text (str): The user input string to generate entity tags for
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
predictions (str): The user input string to generate entity tags for
|
60 |
+
ner_annotation (str): The user input string to generate entity tags for
|
61 |
+
"""
|
62 |
+
|
63 |
+
preds = self.nlp(text)
|
64 |
+
ner_annotation = self.get_annotation(preds, text)
|
65 |
+
return preds, ner_annotation
|
part_of_speech_tagging.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import nltk
|
2 |
+
from nltk.tokenize import word_tokenize
|
3 |
+
nltk.download('punkt')
|
4 |
+
nltk.download('averaged_perceptron_tagger')
|
5 |
+
|
6 |
+
|
7 |
+
class POSTagging:
|
8 |
+
"""Part of Speech Tagging on text data"""
|
9 |
+
|
10 |
+
def __init__(self):
|
11 |
+
pass
|
12 |
+
|
13 |
+
def classify(self, text):
|
14 |
+
"""
|
15 |
+
Generate Part of Speech tags.
|
16 |
+
|
17 |
+
Parameters:
|
18 |
+
text (str): The user input string to generate tags for
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
predictions (list): list of tuples containing words and their respective tags
|
22 |
+
"""
|
23 |
+
|
24 |
+
text = word_tokenize(text)
|
25 |
+
predictions = nltk.pos_tag(text)
|
26 |
+
return predictions
|
requirements.txt
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
scikit-learn
|
2 |
+
tensorflow==2.5.0
|
3 |
+
tensorflow-hub==0.12.0
|
4 |
+
nltk==3.5
|
5 |
+
typing-extensions==3.7.4.3
|
6 |
+
streamlit-option-menu==0.3.2
|
7 |
+
st-annotated-text==3.0.0
|
8 |
+
transformers-interpret==0.7.2
|
9 |
+
htbuilder==0.6.0
|
10 |
+
pytextrank==3.2.3
|
11 |
+
spacy==3.8.3
|
12 |
+
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
|
sentiment_analysis.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
+
from transformers_interpret import SequenceClassificationExplainer
|
3 |
+
import torch
|
4 |
+
import pandas as pd
|
5 |
+
|
6 |
+
|
7 |
+
class SentimentAnalysis:
|
8 |
+
"""
|
9 |
+
Sentiment on text data.
|
10 |
+
|
11 |
+
Attributes:
|
12 |
+
tokenizer: An instance of Hugging Face Tokenizer
|
13 |
+
model: An instance of Hugging Face Model
|
14 |
+
explainer: An instance of SequenceClassificationExplainer from Transformers interpret
|
15 |
+
"""
|
16 |
+
|
17 |
+
def __init__(self):
|
18 |
+
# Load Tokenizer & Model
|
19 |
+
hub_location = 'cardiffnlp/twitter-roberta-base-sentiment'
|
20 |
+
self.tokenizer = AutoTokenizer.from_pretrained(hub_location)
|
21 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(hub_location)
|
22 |
+
|
23 |
+
# Change model labels in config
|
24 |
+
self.model.config.id2label[0] = "Negative"
|
25 |
+
self.model.config.id2label[1] = "Neutral"
|
26 |
+
self.model.config.id2label[2] = "Positive"
|
27 |
+
self.model.config.label2id["Negative"] = self.model.config.label2id.pop("LABEL_0")
|
28 |
+
self.model.config.label2id["Neutral"] = self.model.config.label2id.pop("LABEL_1")
|
29 |
+
self.model.config.label2id["Positive"] = self.model.config.label2id.pop("LABEL_2")
|
30 |
+
|
31 |
+
# Instantiate explainer
|
32 |
+
self.explainer = SequenceClassificationExplainer(self.model, self.tokenizer)
|
33 |
+
|
34 |
+
def justify(self, text):
|
35 |
+
"""
|
36 |
+
Get html annotation for displaying sentiment justification over text.
|
37 |
+
|
38 |
+
Parameters:
|
39 |
+
text (str): The user input string to sentiment justification
|
40 |
+
|
41 |
+
Returns:
|
42 |
+
html (hmtl): html object for plotting sentiment prediction justification
|
43 |
+
"""
|
44 |
+
|
45 |
+
word_attributions = self.explainer(text)
|
46 |
+
html = self.explainer.visualize("example.html")
|
47 |
+
|
48 |
+
return html
|
49 |
+
|
50 |
+
def classify(self, text):
|
51 |
+
"""
|
52 |
+
Recognize Sentiment in text.
|
53 |
+
|
54 |
+
Parameters:
|
55 |
+
text (str): The user input string to perform sentiment classification on
|
56 |
+
|
57 |
+
Returns:
|
58 |
+
predictions (str): The predicted probabilities for sentiment classes
|
59 |
+
"""
|
60 |
+
|
61 |
+
tokens = self.tokenizer.encode_plus(text, add_special_tokens=False, return_tensors='pt')
|
62 |
+
outputs = self.model(**tokens)
|
63 |
+
probs = torch.nn.functional.softmax(outputs[0], dim=-1)
|
64 |
+
probs = probs.mean(dim=0).detach().numpy()
|
65 |
+
predictions = pd.Series(probs, index=["Negative", "Neutral", "Positive"], name='Predicted Probability')
|
66 |
+
|
67 |
+
return predictions
|
68 |
+
|
69 |
+
def run(self, text):
|
70 |
+
"""
|
71 |
+
Classify and Justify Sentiment in text.
|
72 |
+
|
73 |
+
Parameters:
|
74 |
+
text (str): The user input string to perform sentiment classification on
|
75 |
+
|
76 |
+
Returns:
|
77 |
+
predictions (str): The predicted probabilities for sentiment classes
|
78 |
+
html (hmtl): html object for plotting sentiment prediction justification
|
79 |
+
"""
|
80 |
+
|
81 |
+
predictions = self.classify(text)
|
82 |
+
html = self.justify(text)
|
83 |
+
|
84 |
+
return predictions, html
|