AIEcosystem commited on
Commit
77a1bc5
·
verified ·
1 Parent(s): 8c92945

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +389 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,391 @@
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
+
18
+ st.markdown(
19
+ """
20
+ <style>
21
+ /* Overall app container */
22
+ .stApp {
23
+ background-color: #F5F5F5; /* A very light grey */
24
+ color: #333333; /* Dark grey for text for good contrast */
25
+ }
26
+
27
+ /* Sidebar background */
28
+ .css-1d36184, .css-1d36184, .st-ck {
29
+ background-color: #D3D3D3; /* Light grey for the sidebar */
30
+ }
31
+
32
+ /* Expander header and content background */
33
+ .streamlit-expanderHeader, .streamlit-expanderContent {
34
+ background-color: #F5F5F5;
35
+ }
36
+
37
+ /* Text Area background and text color */
38
+ .stTextArea textarea {
39
+ background-color: #E6E6E6; /* Slightly darker grey for input fields */
40
+ color: #000000;
41
+ border: 1px solid #B0B0B0; /* Add a subtle border */
42
+ }
43
+
44
+ /* Button styling */
45
+ .stButton > button {
46
+ background-color: #B0B0B0; /* A medium grey for the button */
47
+ color: #FFFFFF; /* White text for contrast */
48
+ border: none;
49
+ padding: 10px 20px;
50
+ border-radius: 5px;
51
+ }
52
+ .stButton > button:hover {
53
+ background-color: #8C8C8C; /* Darker grey on hover */
54
+ }
55
+
56
+ /* Alert boxes */
57
+ .stAlert {
58
+ color: #000000;
59
+ border-left: 5px solid #8C8C8C; /* A dark grey border for a clean look */
60
+ }
61
+ .stAlert.st-warning {
62
+ background-color: #C0C0C0; /* Silver grey for warning */
63
+ }
64
+ .stAlert.st-success {
65
+ background-color: #C0C0C0; /* Silver grey for success */
66
+ }
67
+ </style>
68
+ """,
69
+ unsafe_allow_html=True
70
+ )
71
+
72
+
73
+
74
+
75
+
76
+ # --- Page Configuration and UI Elements ---
77
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
78
+ st.subheader("Legal Lens", divider="grey")
79
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
80
+ expander = st.expander("**Important notes**")
81
+ expander.write("""**Named Entities:** This Legal Lens web app predicts twenty-eight (28) labels: "Plaintiff", "Defendant", "Appellant", "Appellee", "Debtor", "Creditor", "Signer", "Witness", "Courts", "Judges", "Lawyers", "Attorneys", "Statutes", "Laws", "Provisions", "Case_citations", "Legal_documents", "Effective_dates", "Execution_dates", "Expiration_dates", "Money", "Amounts", "Contract_terms", "Case_number", "Witnesses", "Crimes", "Offenses", "Victims"
82
+
83
+ 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.
84
+
85
+ **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.
86
+
87
+ **Usage Limits:** You can request results unlimited times for one (1) month.
88
+
89
+ **Supported Languages:** English
90
+
91
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
92
+
93
+ For any errors or inquiries, please contact us at info@nlpblogs.com""")
94
+
95
+ with st.sidebar:
96
+ st.write("Use the following code to embed the Legal Lens web app on your website. Feel free to adjust the width and height values to fit your page.")
97
+ code = '''
98
+ <iframe
99
+ src="https://aiecosystem-storycraft.hf.space"
100
+ frameborder="0"
101
+ width="850"
102
+ height="450"
103
+ ></iframe>
104
+ '''
105
+ st.code(code, language="html")
106
+ st.text("")
107
+ st.text("")
108
+ st.divider()
109
+ st.subheader("🚀 Ready to build your own NER Web App?", divider="blue")
110
+ st.link_button("NER Builder", "https://nlpblogs.com", type="primary")
111
+
112
+ # --- Comet ML Setup ---
113
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
114
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
115
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
116
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
117
+
118
+ if not comet_initialized:
119
+ st.warning("Comet ML not initialized. Check environment variables.")
120
+
121
+ # --- Label Definitions ---
122
+
123
+ labels = [
124
+ "Plaintiff",
125
+ "Defendant",
126
+ "Appellant",
127
+ "Appellee",
128
+ "Debtor",
129
+ "Creditor",
130
+ "Signer",
131
+ "Witness",
132
+ "Courts",
133
+ "Judges",
134
+ "Lawyers",
135
+ "Attorneys",
136
+ "Statutes",
137
+ "Laws",
138
+ "Provisions",
139
+ "Case_citations",
140
+ "Legal_documents",
141
+ "Effective_dates",
142
+ "Execution_dates",
143
+ "Expiration_dates",
144
+ "Money",
145
+ "Amounts",
146
+ "Contract_terms",
147
+ "Case_number",
148
+ "Witnesses",
149
+ "Crimes",
150
+ "Offenses",
151
+ "Victims"
152
+ ]
153
+
154
+
155
+
156
+ category_mapping = {
157
+ "Parties": [
158
+ "Plaintiff",
159
+
160
+ "Defendant",
161
+
162
+ "Appellant",
163
+ "Appellee",
164
+ "Debtor",
165
+ "Creditor",
166
+ "Signer",
167
+ "Witness"
168
+ ],
169
+
170
+ "Judicial & Governmental Bodies": [
171
+ "Courts",
172
+ "Judges",
173
+ "Lawyers",
174
+ "Attorneys"
175
+
176
+ ],
177
+
178
+ "Legal Instruments & Concepts": [
179
+ "Statutes",
180
+ "Laws",
181
+ "Provisions",
182
+ "Case_citations",
183
+ "Legal_documents"
184
+
185
+ ],
186
+
187
+ "Dates & Timeframes": [
188
+ "Effective_dates",
189
+ "Execution_dates",
190
+ "Expiration_dates"
191
+
192
+
193
+ ],
194
+
195
+ "Financial & Monetary Entities": [
196
+ "Money",
197
+ "Amounts"
198
+
199
+ ],
200
+
201
+ "Contracts": [
202
+ "Contract_terms"
203
+
204
+ ],
205
+
206
+ "Court Judgments": [
207
+ "Case_number",
208
+ "Witnesses",
209
+
210
+ ],
211
+
212
+
213
+
214
+ "Criminal Law:": [
215
+ "Crimes",
216
+ "Offenses",
217
+ "Victims"
218
+
219
+ ]
220
+
221
+
222
+ }
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+ # --- Model Loading ---
231
+ @st.cache_resource
232
+ def load_ner_model():
233
+ """Loads the GLiNER model and caches it."""
234
+ try:
235
+ return GLiNER.from_pretrained("gliner-community/gliner_large-v2.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
236
+ except Exception as e:
237
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
238
+ st.stop()
239
+ model = load_ner_model()
240
+
241
+ # Flatten the mapping to a single dictionary
242
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
243
+
244
+ # --- Text Input and Clear Button ---
245
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
246
+
247
+ def clear_text():
248
+ """Clears the text area."""
249
+ st.session_state['my_text_area'] = ""
250
+
251
+ st.button("Clear text", on_click=clear_text)
252
+
253
+
254
+ # --- Results Section ---
255
+ if st.button("Results"):
256
+ start_time = time.time()
257
+ if not text.strip():
258
+ st.warning("Please enter some text to extract entities.")
259
+ else:
260
+ with st.spinner("Extracting entities...", show_time=True):
261
+ entities = model.predict_entities(text, labels)
262
+ df = pd.DataFrame(entities)
263
+
264
+ if not df.empty:
265
+ df['category'] = df['label'].map(reverse_category_mapping)
266
+ if comet_initialized:
267
+ experiment = Experiment(
268
+ api_key=COMET_API_KEY,
269
+ workspace=COMET_WORKSPACE,
270
+ project_name=COMET_PROJECT_NAME,
271
+ )
272
+ experiment.log_parameter("input_text", text)
273
+ experiment.log_table("predicted_entities", df)
274
+
275
+ st.subheader("Grouped Entities by Category", divider = "grey")
276
+
277
+ # Create tabs for each category
278
+ category_names = sorted(list(category_mapping.keys()))
279
+ category_tabs = st.tabs(category_names)
280
+
281
+ for i, category_name in enumerate(category_names):
282
+ with category_tabs[i]:
283
+ df_category_filtered = df[df['category'] == category_name]
284
+ if not df_category_filtered.empty:
285
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
286
+ else:
287
+ st.info(f"No entities found for the '{category_name}' category.")
288
+
289
+
290
+
291
+ with st.expander("See Glossary of tags"):
292
+ st.write('''
293
+ - **text**: ['entity extracted from your text data']
294
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
295
+ - **label**: ['label (tag) assigned to a given extracted entity']
296
+ - **start**: ['index of the start of the corresponding entity']
297
+ - **end**: ['index of the end of the corresponding entity']
298
+ ''')
299
+ st.divider()
300
+
301
+ # Tree map
302
+ st.subheader("Tree map", divider = "grey")
303
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
304
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5F5F5', plot_bgcolor='#F5F5F5')
305
+ st.plotly_chart(fig_treemap)
306
+
307
+ # Pie and Bar charts
308
+ grouped_counts = df['category'].value_counts().reset_index()
309
+ grouped_counts.columns = ['category', 'count']
310
+ col1, col2 = st.columns(2)
311
+
312
+ with col1:
313
+ st.subheader("Pie chart", divider = "grey")
314
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
315
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
316
+ fig_pie.update_layout(
317
+ paper_bgcolor='#F5F5F5',
318
+ plot_bgcolor='#F5F5F5'
319
+ )
320
+ st.plotly_chart(fig_pie)
321
+
322
+
323
+
324
 
325
+ with col2:
326
+ st.subheader("Bar chart", divider = "grey")
327
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
328
+ fig_bar.update_layout( # Changed from fig_pie to fig_bar
329
+ paper_bgcolor='#F5F5F5',
330
+ plot_bgcolor='#F5F5F5'
331
+ )
332
+ st.plotly_chart(fig_bar)
333
+
334
+ # Most Frequent Entities
335
+ st.subheader("Most Frequent Entities", divider="grey")
336
+ word_counts = df['text'].value_counts().reset_index()
337
+ word_counts.columns = ['Entity', 'Count']
338
+ repeating_entities = word_counts[word_counts['Count'] > 1]
339
+ if not repeating_entities.empty:
340
+ st.dataframe(repeating_entities, use_container_width=True)
341
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
342
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
343
+ paper_bgcolor='#F5F5F5',
344
+ plot_bgcolor='#F5F5F5')
345
+ st.plotly_chart(fig_repeating_bar)
346
+ else:
347
+ st.warning("No entities were found that occur more than once.")
348
+
349
+ # Download Section
350
+ st.divider()
351
+
352
+ dfa = pd.DataFrame(
353
+ data={
354
+ 'Column Name': ['text', 'label', 'score', 'start', 'end'],
355
+ 'Description': [
356
+ 'entity extracted from your text data',
357
+ 'label (tag) assigned to a given extracted entity',
358
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
359
+ 'index of the start of the corresponding entity',
360
+ 'index of the end of the corresponding entity',
361
+
362
+ ]
363
+ }
364
+ )
365
+ buf = io.BytesIO()
366
+ with zipfile.ZipFile(buf, "w") as myzip:
367
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
368
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
369
+
370
+ with stylable_container(
371
+ key="download_button",
372
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
373
+ ):
374
+ st.download_button(
375
+ label="Download results and glossary (zip)",
376
+ data=buf.getvalue(),
377
+ file_name="nlpblogs_results.zip",
378
+ mime="application/zip",
379
+ )
380
+
381
+ if comet_initialized:
382
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
383
+ experiment.end()
384
+ else: # If df is empty
385
+ st.warning("No entities were found in the provided text.")
386
+
387
+ end_time = time.time()
388
+ elapsed_time = end_time - start_time
389
+ st.text("")
390
+ st.text("")
391
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")