Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files6 unmodified lines789101112131415161734 unmodified lines5253545556575830 unmodified lines8990919293941 unmodified line9697989910010110210312 unmodified lines11611711811912012112219 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872886 unmodified linesimport plotly.express as pximport zipfileimport jsonfrom cryptography.fernet import Fernet # This import is not usedfrom streamlit_extras.stylable_container import stylable_containerfrom typing import Optionalfrom gliner import GLiNERfrom comet_ml import Experiment# --- CSS Styling for the App ---st.markdown("""34 unmodified lines}</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")30 unmodified linesst.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 = ["Product_Name","Product_Type",12 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():"""Loads the GLiNER model and caches it."""try:# The 'labels' variable is now correctly passed to the functionreturn GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)except 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,workspace=COMET_WORKSPACE,project_name=COMET_PROJECT_NAME,)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]if not df_category_filtered.empty:st.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']- **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']- **label**: ['label (tag) assigned to a given extracted entity']- **start**: ['index of the start of the corresponding entity']- **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')fig_pie.update_traces(textposition='inside', textinfo='percent+label')fig_pie.update_layout(paper_bgcolor='#E8F5E9',plot_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')fig_bar.update_layout(paper_bgcolor='#E8F5E9',plot_bgcolor='#E8F5E9')st.plotly_chart(fig_bar)# Most Frequent Entitiesst.subheader("Most Frequent Entities", divider="violet")word_counts = df['text'].value_counts().reset_index()word_counts.columns = ['Entity', 'Count']repeating_entities = word_counts[word_counts['Count'] > 1]if not repeating_entities.empty:st.dataframe(repeating_entities, use_container_width=True)fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},paper_bgcolor='#E8F5E9',plot_bgcolor='#E8F5E9')st.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'],'Description': ['entity extracted from your text data','label (tag) assigned to a given extracted entity','accuracy score; how accurately a tag has been assigned to a given entity','index of the start of the corresponding entity','index of the end of the corresponding entity',]})buf = io.BytesIO()with 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; }""",):st.download_button(label="Download results and glossary (zip)",data=buf.getvalue(),file_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("")st.text("")st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")6 unmodified lines789101112131415161734 unmodified lines52535455565758596030 unmodified lines919293949596971 unmodified line9910010110210310410510612 unmodified lines11912012112212312412512612719 unmodified lines1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403416 unmodified linesimport plotly.express as pximport zipfileimport jsonfrom streamlit_extras.stylable_container import stylable_containerfrom typing import Optionalfrom gliner import GLiNERfrom comet_ml import Experiment# --- CSS Styling for the App ---st.markdown("""34 unmodified lines}</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")30 unmodified linesst.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 ---labels = ["Product_Name","Product_Type",12 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():"""Loads the GLiNER model and caches it."""try:return GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)except 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}# --- Session State Initialization ---if 'show_results' not in st.session_state:st.session_state.show_results = Falseif 'last_text' not in st.session_state:st.session_state.last_text = ""if 'results_df' not in st.session_state:st.session_state.results_df = pd.DataFrame()if 'elapsed_time' not in st.session_state:st.session_state.elapsed_time = 0.0# --- 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 and hides results."""st.session_state['my_text_area'] = ""st.session_state.show_results = Falsest.session_state.last_text = ""st.session_state.results_df = pd.DataFrame()st.session_state.elapsed_time = 0.0st.button("Clear text", on_click=clear_text)# --- Results Section ---if st.button("Results"):if not text.strip():st.warning("Please enter some text to extract entities.")st.session_state.show_results = Falseelif word_count > word_limit:st.warning(f"Your text exceeds the {word_limit} word limit. Please shorten it to continue.")st.session_state.show_results = Falseelse:# Check if the text is different from the last timeif text != st.session_state.last_text:st.session_state.show_results = Truest.session_state.last_text = textstart_time = time.time()with st.spinner("Extracting entities...", show_time=True):entities = model.predict_entities(text, labels)df = pd.DataFrame(entities)st.session_state.results_df = dfif not df.empty:df['category'] = df['label'].map(reverse_category_mapping)if comet_initialized:experiment = Experiment(api_key=COMET_API_KEY,workspace=COMET_WORKSPACE,project_name=COMET_PROJECT_NAME,)experiment.log_parameter("input_text", text)experiment.log_table("predicted_entities", df)experiment.end()end_time = time.time()st.session_state.elapsed_time = end_time - start_timeelse:# If the text is the same, just show the cached results without re-runningst.session_state.show_results = True# Display results if the state variable is Trueif st.session_state.show_results:df = st.session_state.results_dfif not df.empty:df['category'] = df['label'].map(reverse_category_mapping)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]if not df_category_filtered.empty:st.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']- **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']- **label**: ['label (tag) assigned to a given extracted entity']- **start**: ['index of the start of the corresponding entity']- **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')fig_pie.update_traces(textposition='inside', textinfo='percent+label')fig_pie.update_layout(paper_bgcolor='#E8F5E9',plot_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')fig_bar.update_layout(paper_bgcolor='#E8F5E9',plot_bgcolor='#E8F5E9')st.plotly_chart(fig_bar)# Most Frequent Entitiesst.subheader("Most Frequent Entities", divider="violet")word_counts = df['text'].value_counts().reset_index()word_counts.columns = ['Entity', 'Count']repeating_entities = word_counts[word_counts['Count'] > 1]if not repeating_entities.empty:st.dataframe(repeating_entities, use_container_width=True)fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},paper_bgcolor='#E8F5E9',plot_bgcolor='#E8F5E9')st.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'],'Description': ['entity extracted from your text data','label (tag) assigned to a given extracted entity','accuracy score; how accurately a tag has been assigned to a given entity','index of the start of the corresponding entity','index of the end of the corresponding entity',]})buf = io.BytesIO()with 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; }""",):st.download_button(label="Download results and glossary (zip)",data=buf.getvalue(),file_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.")st.text("")st.text("")st.info(f"Results processed in **{st.session_state.elapsed_time:.2f} seconds**.")
src/streamlit_app.py+173-120