AIEcosystem commited on
Commit
c59cf23
Β·
verified Β·
1 Parent(s): 476478b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +28 -23
src/streamlit_app.py CHANGED
@@ -12,6 +12,7 @@ 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
  st.markdown(
16
  """
17
  <style>
@@ -20,36 +21,36 @@ st.markdown(
20
  background-color: #E8F5E9; /* A very light green */
21
  color: #1B5E20; /* Dark green for the text */
22
  }
23
-
24
  /* Sidebar background color */
25
  .css-1d36184 {
26
  background-color: #A5D6A7; /* A medium light green */
27
  secondary-background-color: #A5D6A7;
28
  }
29
-
30
  /* Expander background color and header */
31
  .streamlit-expanderContent, .streamlit-expanderHeader {
32
  background-color: #E8F5E9;
33
  }
34
-
35
  /* Text Area background and text color */
36
  .stTextArea textarea {
37
  background-color: #81C784; /* A slightly darker medium green */
38
  color: #1B5E20; /* Dark green for text */
39
  }
40
-
41
  /* Button background and text color */
42
  .stButton > button {
43
  background-color: #81C784;
44
  color: #1B5E20;
45
  }
46
-
47
  /* Warning box background and text color */
48
  .stAlert.st-warning {
49
  background-color: #66BB6A; /* A medium-dark green for the warning box */
50
  color: #1B5E20;
51
  }
52
-
53
  /* Success box background and text color */
54
  .stAlert.st-success {
55
  background-color: #66BB6A; /* A medium-dark green for the success box */
@@ -58,6 +59,7 @@ st.markdown(
58
  </style>
59
  """,
60
  unsafe_allow_html=True)
 
61
  # --- Page Configuration and UI Elements ---
62
  st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
63
  st.subheader("EntityFinance", divider="violet")
@@ -77,7 +79,6 @@ Results are presented in easy-to-read tables, visualized in an interactive tree
77
 
78
  For any errors or inquiries, please contact us at [email protected]""")
79
 
80
-
81
  with st.sidebar:
82
  st.write("Use the following code to embed the EntityFinance web app on your website. Feel free to adjust the width and height values to fit your page.")
83
  code = '''
@@ -95,6 +96,7 @@ with st.sidebar:
95
  st.divider()
96
  st.subheader("πŸš€ Ready to build your own AI Web App?", divider="violet")
97
  st.link_button("AI Web App Builder", "https://nlpblogs.com/build-your-named-entity-recognition-app/", type="primary")
 
98
  # --- Comet ML Setup ---
99
  COMET_API_KEY = os.environ.get("COMET_API_KEY")
100
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
@@ -102,6 +104,7 @@ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
102
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
103
  if not comet_initialized:
104
  st.warning("Comet ML not initialized. Check environment variables.")
 
105
  # --- Label Definitions ---
106
  labels = [
107
  "Monetary_value",
@@ -118,20 +121,16 @@ labels = [
118
  "Location",
119
  "Date",
120
  "Time"]
 
121
  # Corrected mapping dictionary
122
  # Create a mapping dictionary for labels to categories
123
  category_mapping = {
124
- "People & Groups": [ "Person",
125
- "Organization",
126
- "Regulatory_entity"],
127
- "Financial & Transactional": [ "Monetary_value",
128
- "Financial_instrument",
129
- "Company_identifier",
130
- "Financial_event",
131
- "Financial_metric", "Product", "Service"],
132
  "Temporal": ["Date", "Time"],
133
  "Locations": ["Location"],
134
  "Documents & Context": ["Financial_document"]}
 
135
  # --- Model Loading ---
136
  @st.cache_resource
137
  def load_ner_model():
@@ -144,23 +143,27 @@ def load_ner_model():
144
  model = load_ner_model()
145
  # Flatten the mapping to a single dictionary
146
  reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
 
147
  # --- Text Input and Clear Button ---
148
  word_limit = 200
149
  text = st.text_area(f"Type or paste your text below (max {word_limit} words), and then press Ctrl + Enter", height=250, key='my_text_area')
150
  word_count = len(text.split())
151
  st.markdown(f"**Word count:** {word_count}/{word_limit}")
 
152
  def clear_text():
153
  """Clears the text area."""
154
  st.session_state['my_text_area'] = ""
 
155
  st.button("Clear text", on_click=clear_text)
 
156
  # --- Results Section ---
157
  if st.button("Results"):
158
- start_time = time.time()
159
  if not text.strip():
160
  st.warning("Please enter some text to extract entities.")
161
  elif word_count > word_limit:
162
  st.warning(f"Your text exceeds the {word_limit} word limit. Please shorten it to continue.")
163
  else:
 
164
  with st.spinner("Extracting entities...", show_time=True):
165
  entities = model.predict_entities(text, labels)
166
  df = pd.DataFrame(entities)
@@ -215,7 +218,7 @@ if st.button("Results"):
215
  with col2:
216
  st.subheader("Bar chart", divider = "violet")
217
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
218
- fig_bar.update_layout( # Changed from fig_pie to fig_bar
219
  paper_bgcolor='#E8F5E9',
220
  plot_bgcolor='#E8F5E9'
221
  )
@@ -265,10 +268,12 @@ if st.button("Results"):
265
  if comet_initialized:
266
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
267
  experiment.end()
 
 
 
 
 
 
 
268
  else: # If df is empty
269
- st.warning("No entities were found in the provided text.")
270
- end_time = time.time()
271
- elapsed_time = end_time - start_time
272
- st.text("")
273
- st.text("")
274
- st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
 
12
  from typing import Optional
13
  from gliner import GLiNER
14
  from comet_ml import Experiment
15
+
16
  st.markdown(
17
  """
18
  <style>
 
21
  background-color: #E8F5E9; /* A very light green */
22
  color: #1B5E20; /* Dark green for the text */
23
  }
24
+
25
  /* Sidebar background color */
26
  .css-1d36184 {
27
  background-color: #A5D6A7; /* A medium light green */
28
  secondary-background-color: #A5D6A7;
29
  }
30
+
31
  /* Expander background color and header */
32
  .streamlit-expanderContent, .streamlit-expanderHeader {
33
  background-color: #E8F5E9;
34
  }
35
+
36
  /* Text Area background and text color */
37
  .stTextArea textarea {
38
  background-color: #81C784; /* A slightly darker medium green */
39
  color: #1B5E20; /* Dark green for text */
40
  }
41
+
42
  /* Button background and text color */
43
  .stButton > button {
44
  background-color: #81C784;
45
  color: #1B5E20;
46
  }
47
+
48
  /* Warning box background and text color */
49
  .stAlert.st-warning {
50
  background-color: #66BB6A; /* A medium-dark green for the warning box */
51
  color: #1B5E20;
52
  }
53
+
54
  /* Success box background and text color */
55
  .stAlert.st-success {
56
  background-color: #66BB6A; /* A medium-dark green for the success box */
 
59
  </style>
60
  """,
61
  unsafe_allow_html=True)
62
+
63
  # --- Page Configuration and UI Elements ---
64
  st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
65
  st.subheader("EntityFinance", divider="violet")
 
79
 
80
  For any errors or inquiries, please contact us at [email protected]""")
81
 
 
82
  with st.sidebar:
83
  st.write("Use the following code to embed the EntityFinance web app on your website. Feel free to adjust the width and height values to fit your page.")
84
  code = '''
 
96
  st.divider()
97
  st.subheader("πŸš€ Ready to build your own AI Web App?", divider="violet")
98
  st.link_button("AI Web App Builder", "https://nlpblogs.com/build-your-named-entity-recognition-app/", type="primary")
99
+
100
  # --- Comet ML Setup ---
101
  COMET_API_KEY = os.environ.get("COMET_API_KEY")
102
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
 
104
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
105
  if not comet_initialized:
106
  st.warning("Comet ML not initialized. Check environment variables.")
107
+
108
  # --- Label Definitions ---
109
  labels = [
110
  "Monetary_value",
 
121
  "Location",
122
  "Date",
123
  "Time"]
124
+
125
  # Corrected mapping dictionary
126
  # Create a mapping dictionary for labels to categories
127
  category_mapping = {
128
+ "People & Groups": [ "Person", "Organization", "Regulatory_entity"],
129
+ "Financial & Transactional": [ "Monetary_value", "Financial_instrument", "Company_identifier", "Financial_event", "Financial_metric", "Product", "Service"],
 
 
 
 
 
 
130
  "Temporal": ["Date", "Time"],
131
  "Locations": ["Location"],
132
  "Documents & Context": ["Financial_document"]}
133
+
134
  # --- Model Loading ---
135
  @st.cache_resource
136
  def load_ner_model():
 
143
  model = load_ner_model()
144
  # Flatten the mapping to a single dictionary
145
  reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
146
+
147
  # --- Text Input and Clear Button ---
148
  word_limit = 200
149
  text = st.text_area(f"Type or paste your text below (max {word_limit} words), and then press Ctrl + Enter", height=250, key='my_text_area')
150
  word_count = len(text.split())
151
  st.markdown(f"**Word count:** {word_count}/{word_limit}")
152
+
153
  def clear_text():
154
  """Clears the text area."""
155
  st.session_state['my_text_area'] = ""
156
+
157
  st.button("Clear text", on_click=clear_text)
158
+
159
  # --- Results Section ---
160
  if st.button("Results"):
 
161
  if not text.strip():
162
  st.warning("Please enter some text to extract entities.")
163
  elif word_count > word_limit:
164
  st.warning(f"Your text exceeds the {word_limit} word limit. Please shorten it to continue.")
165
  else:
166
+ start_time = time.time()
167
  with st.spinner("Extracting entities...", show_time=True):
168
  entities = model.predict_entities(text, labels)
169
  df = pd.DataFrame(entities)
 
218
  with col2:
219
  st.subheader("Bar chart", divider = "violet")
220
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
221
+ fig_bar.update_layout(
222
  paper_bgcolor='#E8F5E9',
223
  plot_bgcolor='#E8F5E9'
224
  )
 
268
  if comet_initialized:
269
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
270
  experiment.end()
271
+
272
+ # Correctly placed time calculation
273
+ end_time = time.time()
274
+ elapsed_time = end_time - start_time
275
+ st.text("")
276
+ st.text("")
277
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
278
  else: # If df is empty
279
+ st.warning("No entities were found in the provided text.")