AIEcosystem commited on
Commit
022db66
·
verified ·
1 Parent(s): 6c6469f

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +301 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,303 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ['HF_HOME'] = '/tmp'
3
+ import time
4
  import streamlit as st
5
+ import pandas as pd
6
+ import io
7
+ import plotly.express as px
8
+ import zipfile
9
+ import json
10
+ from cryptography.fernet import Fernet
11
+ from streamlit_extras.stylable_container import stylable_container
12
+ from typing import Optional
13
+ from gliner import GLiNER
14
+ from comet_ml import Experiment
15
+
16
+
17
+ st.markdown(
18
+ """
19
+ <style>
20
+ /* Main app background and text color */
21
+ .stApp {
22
+ background-color: #E8F5E9; /* A very light green */
23
+ color: #1B5E20; /* Dark green for the text */
24
+ }
25
+
26
+ /* Sidebar background color */
27
+ .css-1d36184 {
28
+ background-color: #A5D6A7; /* A medium light green */
29
+ secondary-background-color: #A5D6A7;
30
+ }
31
+
32
+ /* Expander background color and header */
33
+ .streamlit-expanderContent, .streamlit-expanderHeader {
34
+ background-color: #E8F5E9;
35
+ }
36
+
37
+ /* Text Area background and text color */
38
+ .stTextArea textarea {
39
+ background-color: #81C784; /* A slightly darker medium green */
40
+ color: #1B5E20; /* Dark green for text */
41
+ }
42
+
43
+ /* Button background and text color */
44
+ .stButton > button {
45
+ background-color: #81C784;
46
+ color: #1B5E20;
47
+ }
48
+
49
+ /* Warning box background and text color */
50
+ .stAlert.st-warning {
51
+ background-color: #66BB6A; /* A medium-dark green for the warning box */
52
+ color: #1B5E20;
53
+ }
54
+
55
+ /* Success box background and text color */
56
+ .stAlert.st-success {
57
+ background-color: #66BB6A; /* A medium-dark green for the success box */
58
+ color: #1B5E20;
59
+ }
60
+ </style>
61
+ """,
62
+ unsafe_allow_html=True
63
+ )
64
+
65
+
66
+
67
+
68
+
69
+ # --- Page Configuration and UI Elements ---
70
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
71
+ st.subheader("ChainSense", divider="violet")
72
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
73
+
74
+ expander = st.expander("**Important notes**")
75
+ expander.write("""**Named Entities:** This ChainSense web app predicts eight (8) labels:"Location", "Organization", "Product_or_Good", "Date", "Quantity", "Transportation_Mode", "Person", "Document_or_Form_ID"
76
+
77
+ Results are presented in easy-to-read tables, visualized in an interactive tree map, pie chart and bar chart, and are available for download along with a Glossary of tags.
78
+
79
+ **How to Use:** Type or paste your text into the text area below, then press Ctrl + Enter. Click the 'Results' button to extract and tag entities in your text data.
80
+
81
+ **Usage Limits:** You can request results unlimited times for one (1) month.
82
+
83
+ **Supported Languages:** English
84
+
85
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
86
+
87
+ For any errors or inquiries, please contact us at [email protected]""")
88
+
89
+ with st.sidebar:
90
+ st.write("Use the following code to embed the ChainSense web app on your website. Feel free to adjust the width and height values to fit your page.")
91
+ code = '''
92
+ <iframe
93
+ src="https://aiecosystem-entityfinance.hf.space"
94
+ frameborder="0"
95
+ width="850"
96
+ height="450"
97
+ ></iframe>
98
+
99
+ '''
100
+ st.code(code, language="html")
101
+ st.text("")
102
+ st.text("")
103
+ st.divider()
104
+ st.subheader("🚀 Ready to build your own AI Web App?", divider="violet")
105
+ st.link_button("AI Web App Builder", " https://nlpblogs.com/custom-web-app-development/", type="primary")
106
+
107
+ # --- Comet ML Setup ---
108
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
109
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
110
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
111
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
112
+
113
+ if not comet_initialized:
114
+ st.warning("Comet ML not initialized. Check environment variables.")
115
+
116
+ # --- Label Definitions ---
117
+ labels = [
118
+ "Location",
119
+ "Organization",
120
+ "Product_or_Good",
121
+ "Date",
122
+ "Quantity",
123
+ "Transportation_Mode",
124
+ "Person",
125
+ "Document_or_Form_ID"
126
+ ]
127
+
128
+
129
+ # Corrected mapping dictionary
130
+
131
+ # Create a mapping dictionary for labels to categories
132
+ category_mapping = {
133
+ "People & Groups": ["Person", "Organization"],
134
+ "Goods & Transactions": ["Product_or_Good", "Quantity", "Document_or_Form_ID"],
135
+ "Temporal & Events": ["Date", "Transportation_Mode"],
136
+ "Locations": ["Location"]
137
+ }
138
+
139
+
140
+
141
+
142
+ # --- Model Loading ---
143
+ @st.cache_resource
144
+ def load_ner_model():
145
+ """Loads the GLiNER model and caches it."""
146
+ try:
147
+ return GLiNER.from_pretrained("gliner-community/gliner_large-v2.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
148
+ except Exception as e:
149
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
150
+ st.stop()
151
+ model = load_ner_model()
152
+
153
+ # Flatten the mapping to a single dictionary
154
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
155
+
156
+ # --- Text Input and Clear Button ---
157
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
158
+
159
+ def clear_text():
160
+ """Clears the text area."""
161
+ st.session_state['my_text_area'] = ""
162
+
163
+ st.button("Clear text", on_click=clear_text)
164
+
165
+
166
+ # --- Results Section ---
167
+ if st.button("Results"):
168
+ start_time = time.time()
169
+ if not text.strip():
170
+ st.warning("Please enter some text to extract entities.")
171
+ else:
172
+ with st.spinner("Extracting entities...", show_time=True):
173
+ entities = model.predict_entities(text, labels)
174
+ df = pd.DataFrame(entities)
175
+
176
+ if not df.empty:
177
+ df['category'] = df['label'].map(reverse_category_mapping)
178
+ if comet_initialized:
179
+ experiment = Experiment(
180
+ api_key=COMET_API_KEY,
181
+ workspace=COMET_WORKSPACE,
182
+ project_name=COMET_PROJECT_NAME,
183
+ )
184
+ experiment.log_parameter("input_text", text)
185
+ experiment.log_table("predicted_entities", df)
186
+
187
+ st.subheader("Grouped Entities by Category", divider = "violet")
188
+
189
+ # Create tabs for each category
190
+ category_names = sorted(list(category_mapping.keys()))
191
+ category_tabs = st.tabs(category_names)
192
+
193
+ for i, category_name in enumerate(category_names):
194
+ with category_tabs[i]:
195
+ df_category_filtered = df[df['category'] == category_name]
196
+ if not df_category_filtered.empty:
197
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
198
+ else:
199
+ st.info(f"No entities found for the '{category_name}' category.")
200
+
201
+
202
+
203
+ with st.expander("See Glossary of tags"):
204
+ st.write('''
205
+ - **text**: ['entity extracted from your text data']
206
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
207
+ - **label**: ['label (tag) assigned to a given extracted entity']
208
+ - **start**: ['index of the start of the corresponding entity']
209
+ - **end**: ['index of the end of the corresponding entity']
210
+ ''')
211
+ st.divider()
212
+
213
+ # Tree map
214
+ st.subheader("Tree map", divider = "violet")
215
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
216
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')
217
+ st.plotly_chart(fig_treemap)
218
+
219
+ # Pie and Bar charts
220
+ grouped_counts = df['category'].value_counts().reset_index()
221
+ grouped_counts.columns = ['category', 'count']
222
+ col1, col2 = st.columns(2)
223
+
224
+ with col1:
225
+ st.subheader("Pie chart", divider = "violet")
226
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
227
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
228
+ fig_pie.update_layout(
229
+ paper_bgcolor='#E8F5E9',
230
+ plot_bgcolor='#E8F5E9'
231
+ )
232
+ st.plotly_chart(fig_pie)
233
+
234
+
235
+
236
 
237
+ with col2:
238
+ st.subheader("Bar chart", divider = "violet")
239
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
240
+ fig_bar.update_layout( # Changed from fig_pie to fig_bar
241
+ paper_bgcolor='#E8F5E9',
242
+ plot_bgcolor='#E8F5E9'
243
+ )
244
+ st.plotly_chart(fig_bar)
245
+
246
+ # Most Frequent Entities
247
+ st.subheader("Most Frequent Entities", divider="violet")
248
+ word_counts = df['text'].value_counts().reset_index()
249
+ word_counts.columns = ['Entity', 'Count']
250
+ repeating_entities = word_counts[word_counts['Count'] > 1]
251
+ if not repeating_entities.empty:
252
+ st.dataframe(repeating_entities, use_container_width=True)
253
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
254
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
255
+ paper_bgcolor='#E8F5E9',
256
+ plot_bgcolor='#E8F5E9')
257
+ st.plotly_chart(fig_repeating_bar)
258
+ else:
259
+ st.warning("No entities were found that occur more than once.")
260
+
261
+ # Download Section
262
+ st.divider()
263
+
264
+ dfa = pd.DataFrame(
265
+ data={
266
+ 'Column Name': ['text', 'label', 'score', 'start', 'end'],
267
+ 'Description': [
268
+ 'entity extracted from your text data',
269
+ 'label (tag) assigned to a given extracted entity',
270
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
271
+ 'index of the start of the corresponding entity',
272
+ 'index of the end of the corresponding entity',
273
+
274
+ ]
275
+ }
276
+ )
277
+ buf = io.BytesIO()
278
+ with zipfile.ZipFile(buf, "w") as myzip:
279
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
280
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
281
+
282
+ with stylable_container(
283
+ key="download_button",
284
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
285
+ ):
286
+ st.download_button(
287
+ label="Download results and glossary (zip)",
288
+ data=buf.getvalue(),
289
+ file_name="nlpblogs_results.zip",
290
+ mime="application/zip",
291
+ )
292
+
293
+ if comet_initialized:
294
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
295
+ experiment.end()
296
+ else: # If df is empty
297
+ st.warning("No entities were found in the provided text.")
298
+
299
+ end_time = time.time()
300
+ elapsed_time = end_time - start_time
301
+ st.text("")
302
+ st.text("")
303
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")