AIEcosystem commited on
Commit
90b72c6
·
verified ·
1 Parent(s): b9da777

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +299 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,301 @@
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: white;
23
+ color: black;
24
+ }
25
+ /* Sidebar background color */
26
+ .css-1d36184 {
27
+ background-color: #ADD8E6;
28
+ secondary-background-color: #ADD8E6;
29
+ }
30
+
31
+ /* Expander background color */
32
+ .streamlit-expanderContent {
33
+ background-color: white;
34
+ }
35
+ /* Expander header background color */
36
+ .streamlit-expanderHeader {
37
+ background-color: white;
38
+ }
39
+ /* Text Area background and text color */
40
+ .stTextArea textarea {
41
+ background-color: lavender;
42
+ color: black;
43
+ }
44
+ /* Button background and text color */
45
+ .stButton > button {
46
+ background-color: lavender;
47
+ color: black;
48
+ }
49
+ /* Warning box background and text color */
50
+ .stAlert.st-warning {
51
+ background-color: #lavender;
52
+ color: black;
53
+ }
54
+ /* Success box background and text color */
55
+ .stAlert.st-success {
56
+ background-color: #lavender;
57
+ color: black;
58
+ }
59
+ </style>
60
+ """,
61
+ unsafe_allow_html=True
62
+ )
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
+
72
+ st.subheader("ProductTag", divider="gray")
73
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
74
+
75
+ expander = st.expander("**Important notes on the ProductTag**")
76
+ expander.write("""
77
+ **Named Entities:** This ProductTag predicts twenty-four (24) labels: "Product", "Service", "Organization", "Company", "Currency", "City", "Country", "Region", "Market", "Store", "Shop", "Customer_segment", "Demographics", "Target_market", "Market_segment", "Fiscal_period", "Timeframe", "Date", "Campaign", "Advertisement", "Event", "Media_platform", "Media_channel", "Social_media_platform"
78
+
79
+ 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.
80
+
81
+ **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.
82
+
83
+ **Usage Limits:** You can request results unlimited times for one (1) week.
84
+
85
+ **Supported Languages:** English
86
+
87
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
88
+
89
+ For any errors or inquiries, please contact us at [email protected]
90
+ """)
91
+
92
+ with st.sidebar:
93
+ st.subheader("Build your own NER Web App in a minute without writing a single line of code.", divider="gray")
94
+ st.link_button("NER File Builder", "https://nlpblogs.com/shop/named-entity-recognition-ner/ner-file-builder/", type="primary")
95
+
96
+ st.text("")
97
+ st.text("")
98
+
99
+ st.write("Use the following code to embed the ProductTag web app on your website. Feel free to adjust the width and height values to fit your page.")
100
+ code = '''
101
+ <iframe
102
+ src="https://aiecosystem-producttag1.hf.space"
103
+ frameborder="0"
104
+ width="850"
105
+ height="450"
106
+ ></iframe>
107
+ '''
108
+ st.code(code, language="html")
109
+
110
+ # --- Comet ML Setup ---
111
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
112
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
113
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
114
+
115
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
116
+ if not comet_initialized:
117
+ st.warning("Comet ML not initialized. Check environment variables.")
118
+
119
+
120
+ # --- Label Definitions ---
121
+ labels = [
122
+ "Fruits Vegetables",
123
+ "Lactose, Diary, Eggs, Cheese, Yoghurt",
124
+ "Meat, Fish, Seafood",
125
+ "Frozen, Prepared Meals",
126
+ "Baking, Cooking",
127
+ "Cereals, Grains, Canned, Seeds",
128
+ "Breads",
129
+ "Snacks, Pastries, Treats",
130
+ "Frozen Desserts",
131
+ "Hot Drinks, Chilled Drinks",
132
+ "Alcoholic Drinks",
133
+ "Spices, Sauces",
134
+ "World Foods",
135
+ "Dietary Restrictions, Health, Allergens, Lifestyle"
136
+ ]
137
+ # Create a mapping dictionary for labels to categories
138
+ category_mapping = {
139
+
140
+ "Fresh & Primary Ingredients": ["Fruits Vegetables", "Meat, Fish, Seafood", "Lactose, Diary, Eggs, Cheese, Yoghurt"],
141
+ "Pantry & Staple Goods" :["Cereals, Grains, Canned, Seeds", "Breads", "Spices, Sauces", "Baking, Cooking"],
142
+ "Prepared & Convenience Foods": ["Frozen, Prepared Meals", "Snacks, Pastries, Treats", "Frozen Desserts", "World Foods"],
143
+ "Beverages": ["Alcoholic Drinks", "Alcoholic Drinks"],
144
+ "Meta-Labels & Lifestyle": ["Dietary Restrictions, Health, Allergens, Lifestyle"]
145
+
146
+ }
147
+
148
+ # --- Model Loading ---
149
+ @st.cache_resource
150
+ def load_ner_model():
151
+ """Loads the GLiNER model and caches it."""
152
+ try:
153
+ return GLiNER.from_pretrained("knowledgator/gliner-decoder-large-v1.0", nested_ner=True, num_gen_sequences=2, gen_constraints= labels, threshold = 0.7)
154
+ except Exception as e:
155
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
156
+ st.stop()
157
+
158
+ model = load_ner_model()
159
+
160
+
161
+ # Flatten the mapping to a single dictionary
162
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
163
+
164
+ # --- Text Input and Clear Button ---
165
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
166
+
167
+ def clear_text():
168
+ """Clears the text area."""
169
+ st.session_state['my_text_area'] = ""
170
+
171
+ st.button("Clear text", on_click=clear_text)
172
+ st.divider()
173
+
174
+ # --- Results Section ---
175
+ if st.button("Results"):
176
+ start_time = time.time()
177
+ if not text.strip():
178
+ st.warning("Please enter some text to extract entities.")
179
+ else:
180
+ with st.spinner("Extracting entities...", show_time=True):
181
+ entities = model.predict_entities(text, labels)
182
+ df = pd.DataFrame(entities)
183
+
184
+ if not df.empty:
185
+ df['category'] = df['label'].map(reverse_category_mapping)
186
+
187
+ if comet_initialized:
188
+ experiment = Experiment(
189
+ api_key=COMET_API_KEY,
190
+ workspace=COMET_WORKSPACE,
191
+ project_name=COMET_PROJECT_NAME,
192
+ )
193
+ experiment.log_parameter("input_text", text)
194
+ experiment.log_table("predicted_entities", df)
195
+
196
+ st.subheader("Extracted Entities", divider = "gray")
197
+ st.dataframe(df.style.set_properties(**{"border": "2px solid gray", "color": "blue", "font-size": "16px"}))
198
+
199
+ with st.expander("See Glossary of tags"):
200
+ st.write('''
201
+ - **text**: ['entity extracted from your text data']
202
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
203
+ - **label**: ['label (tag) assigned to a given extracted entity']
204
+ - **category**: ['the high-level category for the label']
205
+ - **start**: ['index of the start of the corresponding entity']
206
+ - **end**: ['index of the end of the corresponding entity']
207
+ ''')
208
+
209
+ st.divider()
210
+
211
+
212
+ # Tree map
213
+ st.subheader("Tree map", divider = "gray")
214
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
215
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
216
+
217
+
218
+ st.plotly_chart(fig_treemap)
219
+
220
+ # Pie and Bar charts
221
+ grouped_counts = df['category'].value_counts().reset_index()
222
+ grouped_counts.columns = ['category', 'count']
223
+
224
+ col1, col2 = st.columns(2)
225
+ with col1:
226
+ st.subheader("Pie chart", divider = "gray")
227
+ fig_pie = px.pie(grouped_counts, values='count', names='category',
228
+ hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
229
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
230
+ st.plotly_chart(fig_pie)
231
+
232
+ with col2:
233
+ st.subheader("Bar chart", divider = "gray")
234
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True,
235
+ title='Occurrences of predicted categories')
236
+ st.plotly_chart(fig_bar)
237
+
238
+ # Most Frequent Entities
239
+ st.subheader("Most Frequent Entities", divider="gray")
240
+ word_counts = df['text'].value_counts().reset_index()
241
+ word_counts.columns = ['Entity', 'Count']
242
+ repeating_entities = word_counts[word_counts['Count'] > 1]
243
+ if not repeating_entities.empty:
244
+ st.dataframe(repeating_entities, use_container_width=True)
245
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
246
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'})
247
+ st.plotly_chart(fig_repeating_bar)
248
+ else:
249
+ st.warning("No entities were found that occur more than once.")
250
+
251
+
252
+
253
+
254
+
255
+
256
+ # Download Section
257
+ st.divider()
258
+
259
+ dfa = pd.DataFrame(
260
+ data={
261
+ 'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
262
+ 'Description': [
263
+ 'entity extracted from your text data',
264
+ 'label (tag) assigned to a given extracted entity',
265
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
266
+ 'index of the start of the corresponding entity',
267
+ 'index of the end of the corresponding entity',
268
+ 'the broader category the entity belongs to',
269
+ ]
270
+ }
271
+ )
272
+
273
+ buf = io.BytesIO()
274
+ with zipfile.ZipFile(buf, "w") as myzip:
275
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
276
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
277
+
278
+ with stylable_container(
279
+ key="download_button",
280
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
281
+ ):
282
+ st.download_button(
283
+ label="Download results and glossary (zip)",
284
+ data=buf.getvalue(),
285
+ file_name="markettag_results.zip",
286
+ mime="application/zip",
287
+ )
288
+
289
+ if comet_initialized:
290
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
291
+ experiment.end()
292
+
293
+ else: # If df is empty
294
+ st.warning("No entities were found in the provided text.")
295
+
296
+ end_time = time.time()
297
+ elapsed_time = end_time - start_time
298
 
299
+ st.text("")
300
+ st.text("")
301
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")