Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files11 unmodified lines121314151617183 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556571 unmodified line59606162636465666768697071727374757610 unmodified lines878889909192939495969798991 unmodified line1011021031041051061071 unmodified line10911011111211311411514 unmodified lines13013113213313413513613713819 unmodified lines1581591601611621631641651664 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032 unmodified lines2062072082092102112122132142152162172181 unmodified line2202212222232242252263 unmodified lines2302312322332342352362372382392402412422432442452462473 unmodified lines2512522532542552562572 unmodified lines26026126226326426526610 unmodified lines27727827928028128228328428528610 unmodified lines2972982993003013023034 unmodified lines30830931031131231331431531631731831932011 unmodified linesfrom typing import Optionalfrom gliner import GLiNERfrom comet_ml import Experiment# --- CSS Styling for the App ---st.markdown("""3 unmodified linesbackground-color: #E8F5E9; /* A very light green */color: #1B5E20; /* Dark green for the text */}/* Sidebar background color */.css-1d36184 {background-color: #A5D6A7; /* A medium light green */secondary-background-color: #A5D6A7;}/* Expander background color and header */.streamlit-expanderContent, .streamlit-expanderHeader {background-color: #E8F5E9;}/* Text Area background and text color */.stTextArea textarea {background-color: #81C784; /* A slightly darker medium green */color: #1B5E20; /* Dark green for text */}/* Button background and text color */.stButton > button {background-color: #81C784;color: #1B5E20;}/* Warning box background and text color */.stAlert.st-warning {background-color: #66BB6A; /* A medium-dark green for the warning box */color: #1B5E20;}/* Success box background and text color */.stAlert.st-success {background-color: #66BB6A; /* A medium-dark green for the success box */1 unmodified line}</style>""",unsafe_allow_html=True)# --- Page Configuration and UI Elements ---st.set_page_config(layout="wide", page_title="Named Entity Recognition App")st.subheader("RetailTag", divider="violet")st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")expander = st.expander("**Important notes**")expander.write("""**Named Entities:** This RetailTag web app predicts eighteen (18) labels:"Product_Name", "Product_Type", "Brand", "Model_Number", "SKU", "Product_Attribute", "Service_Type", "Order_Number", "Monetary_Value", "Payment_Method", "Discount", "Shipping_Method", "Quantity", "Organization", "Location", "Person", "Date", "Time"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.10 unmodified lineswith st.sidebar:st.write("Use the following code to embed the RetailTag web app on your website. Feel free to adjust the width and height values to fit your page.")code = '''<iframesrc="https://aiecosystem-retailtag.hf.space"frameborder="0"width="850"height="450"></iframe>'''st.code(code, language="html")st.text("")1 unmodified linest.divider()st.subheader("🚀 Ready to build your own AI Web App?", divider="violet")st.link_button("AI Web App Builder", "https://nlpblogs.com/build-your-named-entity-recognition-app/", type="primary")# --- Comet ML Setup ---COMET_API_KEY = os.environ.get("COMET_API_KEY")COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")1 unmodified linecomet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)if not comet_initialized:st.warning("Comet ML not initialized. Check environment variables.")# --- Label Definitions ---# The list of labels is assigned to a variable for use in the model loading functionlabels = [14 unmodified lines"Location","Person","Date","Time"]# Create a mapping dictionary for labels to categoriescategory_mapping = {"Product & Service Entities": [19 unmodified lines"Person","Date","Time"]}# --- Model Loading ---@st.cache_resourcedef load_ner_model():4 unmodified linesexcept Exception as e:st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")st.stop()model = load_ner_model()# Flatten the mapping to a single dictionaryreverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}# --- Text Input and Clear Button ---text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')def clear_text():"""Clears the text area."""st.session_state['my_text_area'] = ""st.button("Clear text", on_click=clear_text)# --- Results Section ---if st.button("Results"):start_time = time.time()if not text.strip():st.warning("Please enter some text to extract entities.")else:with st.spinner("Extracting entities...", show_time=True):entities = model.predict_entities(text, labels)df = pd.DataFrame(entities)if not df.empty:df['category'] = df['label'].map(reverse_category_mapping)if comet_initialized:experiment = Experiment(api_key=COMET_API_KEY,2 unmodified lines)experiment.log_parameter("input_text", text)experiment.log_table("predicted_entities", df)st.subheader("Grouped Entities by Category", divider="violet")# Create tabs for each categorycategory_names = sorted(list(category_mapping.keys()))category_tabs = st.tabs(category_names)for i, category_name in enumerate(category_names):with category_tabs[i]:df_category_filtered = df[df['category'] == category_name]1 unmodified linest.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)else:st.info(f"No entities found for the '{category_name}' category.")with st.expander("See Glossary of tags"):st.write('''- **text**: ['entity extracted from your text data']3 unmodified lines- **end**: ['index of the end of the corresponding entity']''')st.divider()# Tree mapst.subheader("Tree map", divider="violet")fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')st.plotly_chart(fig_treemap)# Pie and Bar chartsgrouped_counts = df['category'].value_counts().reset_index()grouped_counts.columns = ['category', 'count']col1, col2 = st.columns(2)with col1:st.subheader("Pie chart", divider="violet")fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')3 unmodified linesplot_bgcolor='#E8F5E9')st.plotly_chart(fig_pie)with col2:st.subheader("Bar chart", divider="violet")fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')2 unmodified linesplot_bgcolor='#E8F5E9')st.plotly_chart(fig_bar)# Most Frequent Entitiesst.subheader("Most Frequent Entities", divider="violet")word_counts = df['text'].value_counts().reset_index()10 unmodified linesst.plotly_chart(fig_repeating_bar)else:st.warning("No entities were found that occur more than once.")# Download Sectionst.divider()dfa = pd.DataFrame(data={'Column Name': ['text', 'label', 'score', 'start', 'end'],10 unmodified lineswith zipfile.ZipFile(buf, "w") as myzip:myzip.writestr("Summary of the results.csv", df.to_csv(index=False))myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))with stylable_container(key="download_button",css_styles="""button { background-color: #81C784; border: 1px solid black; padding: 5px; color: #1B5E20; }""",4 unmodified linesfile_name="nlpblogs_results.zip",mime="application/zip",)if comet_initialized:experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")experiment.end()else: # If df is emptyst.warning("No entities were found in the provided text.")end_time = time.time()elapsed_time = end_time - start_timest.text("")11 unmodified lines1213141516173 unmodified lines2122232425262728293031323334353637383940414243444546474849501 unmodified line5253545556575859606162636410 unmodified lines757677787980811 unmodified line8384858687881 unmodified line90919293949514 unmodified lines11011111211311411511619 unmodified lines1361371381391401411424 unmodified lines1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761772 unmodified lines1801811821831841851861871881891 unmodified line1911921931941951963 unmodified lines2002012022032042052062072082092102112122132143 unmodified lines2182192202212222232 unmodified lines22622722822923023110 unmodified lines24224324424524624724824910 unmodified lines2602612622632642654 unmodified lines27027127227327427527627727827928011 unmodified linesfrom typing import Optionalfrom gliner import GLiNERfrom comet_ml import Experiment# --- CSS Styling for the App ---st.markdown("""3 unmodified linesbackground-color: #E8F5E9; /* A very light green */color: #1B5E20; /* Dark green for the text */}/* Sidebar background color */.css-1d36184 {background-color: #A5D6A7; /* A medium light green */secondary-background-color: #A5D6A7;}/* Expander background color and header */.streamlit-expanderContent, .streamlit-expanderHeader {background-color: #E8F5E9;}/* Text Area background and text color */.stTextArea textarea {background-color: #81C784; /* A slightly darker medium green */color: #1B5E20; /* Dark green for text */}/* Button background and text color */.stButton > button {background-color: #81C784;color: #1B5E20;}/* Warning box background and text color */.stAlert.st-warning {background-color: #66BB6A; /* A medium-dark green for the warning box */color: #1B5E20;}/* Success box background and text color */.stAlert.st-success {background-color: #66BB6A; /* A medium-dark green for the success box */1 unmodified line}</style>""",unsafe_allow_html=True)# --- Page Configuration and UI Elements ---st.set_page_config(layout="wide", page_title="Named Entity Recognition App")st.subheader("RetailTag", divider="violet")st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")expander = st.expander("**Important notes**")expander.write("""**Named Entities:** This RetailTag web app predicts eighteen (18) labels: "Product_Name", "Product_Type", "Brand", "Model_Number", "SKU", "Product_Attribute", "Service_Type", "Order_Number", "Monetary_Value", "Payment_Method", "Discount", "Shipping_Method", "Quantity", "Organization", "Location", "Person", "Date", "Time"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.10 unmodified lineswith st.sidebar:st.write("Use the following code to embed the RetailTag web app on your website. Feel free to adjust the width and height values to fit your page.")code = '''<iframe src="https://aiecosystem-retailtag.hf.space" frameborder="0" width="850" height="450" ></iframe>'''st.code(code, language="html")st.text("")1 unmodified linest.divider()st.subheader("🚀 Ready to build your own AI Web App?", divider="violet")st.link_button("AI Web App Builder", "https://nlpblogs.com/build-your-named-entity-recognition-app/", type="primary")# --- Comet ML Setup ---COMET_API_KEY = os.environ.get("COMET_API_KEY")COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")1 unmodified linecomet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)if not comet_initialized:st.warning("Comet ML not initialized. Check environment variables.")# --- Label Definitions ---# The list of labels is assigned to a variable for use in the model loading functionlabels = [14 unmodified lines"Location","Person","Date","Time"]# Create a mapping dictionary for labels to categoriescategory_mapping = {"Product & Service Entities": [19 unmodified lines"Person","Date","Time"]}# --- Model Loading ---@st.cache_resourcedef load_ner_model():4 unmodified linesexcept Exception as e:st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")st.stop()model = load_ner_model()# Flatten the mapping to a single dictionaryreverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}# --- Text Input and Clear Button ---word_limit = 200text = 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')word_count = len(text.split())st.markdown(f"**Word count:** {word_count}/{word_limit}")def clear_text():"""Clears the text area."""st.session_state['my_text_area'] = ""st.button("Clear text", on_click=clear_text)# --- Results Section ---if st.button("Results"):start_time = time.time()if not text.strip():st.warning("Please enter some text to extract entities.")elif word_count > word_limit:st.warning(f"Your text exceeds the {word_limit} word limit. Please shorten it to continue.")else:with st.spinner("Extracting entities...", show_time=True):entities = model.predict_entities(text, labels)df = pd.DataFrame(entities)if not df.empty:df['category'] = df['label'].map(reverse_category_mapping)if comet_initialized:experiment = Experiment(api_key=COMET_API_KEY,2 unmodified lines)experiment.log_parameter("input_text", text)experiment.log_table("predicted_entities", df)st.subheader("Grouped Entities by Category", divider="violet")# Create tabs for each categorycategory_names = sorted(list(category_mapping.keys()))category_tabs = st.tabs(category_names)for i, category_name in enumerate(category_names):with category_tabs[i]:df_category_filtered = df[df['category'] == category_name]1 unmodified linest.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)else:st.info(f"No entities found for the '{category_name}' category.")with st.expander("See Glossary of tags"):st.write('''- **text**: ['entity extracted from your text data']3 unmodified lines- **end**: ['index of the end of the corresponding entity']''')st.divider()# Tree mapst.subheader("Tree map", divider="violet")fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')st.plotly_chart(fig_treemap)# Pie and Bar chartsgrouped_counts = df['category'].value_counts().reset_index()grouped_counts.columns = ['category', 'count']col1, col2 = st.columns(2)with col1:st.subheader("Pie chart", divider="violet")fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')3 unmodified linesplot_bgcolor='#E8F5E9')st.plotly_chart(fig_pie)with col2:st.subheader("Bar chart", divider="violet")fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')2 unmodified linesplot_bgcolor='#E8F5E9')st.plotly_chart(fig_bar)# Most Frequent Entitiesst.subheader("Most Frequent Entities", divider="violet")word_counts = df['text'].value_counts().reset_index()10 unmodified linesst.plotly_chart(fig_repeating_bar)else:st.warning("No entities were found that occur more than once.")# Download Sectionst.divider()dfa = pd.DataFrame(data={'Column Name': ['text', 'label', 'score', 'start', 'end'],10 unmodified lineswith zipfile.ZipFile(buf, "w") as myzip:myzip.writestr("Summary of the results.csv", df.to_csv(index=False))myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))with stylable_container(key="download_button",css_styles="""button { background-color: #81C784; border: 1px solid black; padding: 5px; color: #1B5E20; }""",4 unmodified linesfile_name="nlpblogs_results.zip",mime="application/zip",)if comet_initialized:experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")experiment.end()else: # If df is emptyst.warning("No entities were found in the provided text.")end_time = time.time()elapsed_time = end_time - start_timest.text("")
src/streamlit_app.py+11-51