Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files21 unmodified lines222324252627283 unmodified lines323334353637383940417 unmodified lines495051525354551 unmodified line57585960616263646566676869707172737475769 unmodified lines868788899091928 unmodified lines1011021031041051061071081091101112 unmodified lines1141151161171181191201 unmodified line1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501 unmodified line15215315415515615715815916016116216316416516616716817 unmodified lines1861871881891901911921 unmodified line19419519619719819920016 unmodified lines2172182192202212222231 unmodified line2252262272282292302312322332342355 unmodified lines2412422432442452462472 unmodified lines2502512522532542552562572582593 unmodified lines2632642652662672682693 unmodified lines2732742752762772782792 unmodified lines2822832842852862872885 unmodified lines2942952962972982993003013023033043053063073083093103113123133143 unmodified lines3183193203213223233243253263273283296 unmodified lines33633733833934034134234334434534634734834935035118 unmodified lines37037137237337437537637721 unmodified lines3994004014024034044054062 unmodified lines4094104114124134144154164174183 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544557 unmodified lines46346446546646746846936 unmodified lines5065075085095105115125135145157 unmodified lines5235245255265275285295305315325335345355365375385395405415421 unmodified line5445455465475485495501 unmodified line55255355455555655755855956056111 unmodified lines57357457557657757857940 unmodified lines6206216226236246256268 unmodified lines63563663763863964064110 unmodified lines6526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277282 unmodified lines7317327337347357367377387397407417427437447451 unmodified line74774874975075175275375475575675722 unmodified lines7807817827837847857867877887897907916 unmodified lines7987998008018028038048058068078088098108118128138148158168178188198208218228238248255 unmodified lines8318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648651 unmodified line8678688698708718728738748758768778788794 unmodified lines88488588688788888989089189289389412 unmodified lines90790890991021 unmodified lines# ------------------------------from gliner import GLiNERfrom streamlit_extras.stylable_container import stylable_container# Using a try/except for comet_ml importtry:from comet_ml import Experiment3 unmodified linesdef log_parameter(self, *args): passdef log_table(self, *args): passdef end(self): pass# --- Model Home Directory (Fix for deployment environments) ---os.environ['HF_HOME'] = '/tmp'# --- Fixed Label Definitions and Mappings (Used as Fallback) ---FIXED_LABELS = ["person", "country", "city", "organization", "date", "time", "cardinal", "money", "position"]FIXED_ENTITY_COLOR_MAP = {7 unmodified lines"money": "#f43f5e", # Red"position": "#a855f7", # Violet}# --- Fixed Category Mapping ---FIXED_CATEGORY_MAPPING = {"People & Roles": ["person", "organization", "position"],1 unmodified line"Time & Dates": ["date", "time"],"Numbers & Finance": ["money", "cardinal"]}REVERSE_FIXED_CATEGORY_MAPPING = {label: category for category, label_list in FIXED_CATEGORY_MAPPING.items() for label in label_list}# --- Dynamic Color Generator for Custom Labels ---# Use Plotly's Alphabet set for a large pool of distinct colorsCOLOR_PALETTE = cycle(px.colors.qualitative.Alphabet)def extract_label(node_name):"""Extracts the label from a node string like 'Text (Label)'."""match = re.search(r'\(([^)]+)\)$', node_name)return match.group(1) if match else "Unknown"def remove_trailing_punctuation(text_string):"""Removes trailing punctuation from a string."""return text_string.rstrip(string.punctuation)def get_dynamic_color_map(active_labels, fixed_map):"""Generates a color map, using fixed colors if available, otherwise dynamic colors."""color_map = {}9 unmodified lines# Generate a new color from the palettecolor_map[label] = next(COLOR_PALETTE)return color_mapdef highlight_entities(text, df_entities, entity_color_map):"""Generates HTML to display text with entities highlighted and colored.8 unmodified lines# Ensure the entity indices are within the bounds of the full textstart = max(0, entity['start'])end = min(len(text), entity['end'])# Get entity text from the full document based on its indices# The 'text' column in the dataframe is now an attribute of the chunked text, not the original spanentity_text_from_full_doc = text[start:end]label = entity['label']color = entity_color_map.get(label, '#000000')# Create a span with background color and tooltip2 unmodified lineshighlighted_text = highlighted_text[:start] + highlight_html + highlighted_text[end:]# Use a div to mimic the Streamlit input box style for the reportreturn f'<div style="border: 1px solid #888888; padding: 15px; border-radius: 5px; background-color: #ffffff; font-family: monospace; white-space: pre-wrap; margin-bottom: 20px;">{highlighted_text}</div>'def perform_topic_modeling(df_entities, num_topics=2, num_top_words=10):"""Performs basic Topic Modeling using LDA."""documents = df_entities['text'].unique().tolist()1 unmodified line# but here we use the extracted entity texts as per the original code's intent.if len(documents) < 2:return NoneN = min(num_top_words, len(documents))try:tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, stop_words='english', ngram_range=(1, 3))tfidf = tfidf_vectorizer.fit_transform(documents)tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()if len(tfidf_feature_names) < num_topics:tfidf_vectorizer = TfidfVectorizer(max_df=1.0, min_df=1, stop_words='english', ngram_range=(1, 3))tfidf = tfidf_vectorizer.fit_transform(documents)tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()if len(tfidf_feature_names) < num_topics:return Nonelda = LatentDirichletAllocation(n_components=num_topics, max_iter=5, learning_method='online', random_state=42, n_jobs=-1)lda.fit(tfidf)topic_data_list = []for topic_idx, topic in enumerate(lda.components_):top_words_indices = topic.argsort()[:-N - 1:-1]top_words = [tfidf_feature_names[i] for i in top_words_indices]word_weights = [topic[i] for i in top_words_indices]for word, weight in zip(top_words, word_weights):topic_data_list.append({'Topic_ID': f'Topic #{topic_idx + 1}',1 unmodified line'Weight': weight,})return pd.DataFrame(topic_data_list)except Exception as e:return Nonedef create_topic_word_bubbles(df_topic_data):"""Generates a Plotly Bubble Chart for top words across all topics."""df_topic_data = df_topic_data.rename(columns={'Topic_ID': 'topic','Word': 'word', 'Weight': 'weight'})df_topic_data['x_pos'] = df_topic_data.indexif df_topic_data.empty:return Nonefig = px.scatter(df_topic_data,x='x_pos', y='weight', size='weight', color='topic', text='word', hover_name='word', size_max=40,17 unmodified linesmarker=dict(line=dict(width=1, color='DarkSlateGrey')))return figdef generate_network_graph(df, raw_text, entity_color_map):"""Generates a network graph visualization (Node Plot) with edges based on entity co-occurrence in sentences."""entity_counts = df['text'].value_counts().reset_index()1 unmodified lineunique_entities = df.drop_duplicates(subset=['text', 'label']).merge(entity_counts, on='text')if unique_entities.shape[0] < 2:return go.Figure().update_layout(title="Not enough unique entities for a meaningful graph.")num_nodes = len(unique_entities)thetas = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False)radius = 1016 unmodified linesnode2 = unique_entities_in_sentence[j]edge_tuple = tuple(sorted((node1, node2)))edges.add(edge_tuple)edge_x = []edge_y = []for edge in edges:1 unmodified lineif n1 in pos_map and n2 in pos_map:edge_x.extend([pos_map[n1]['x'], pos_map[n2]['x'], None])edge_y.extend([pos_map[n1]['y'], pos_map[n2]['y'], None])fig = go.Figure()edge_trace = go.Scatter(x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines', name='Co-occurrence Edges', showlegend=False)fig.add_trace(edge_trace)fig.add_trace(go.Scatter(x=unique_entities['x'], y=unique_entities['y'], mode='markers+text', name='Entities', text=unique_entities['text'], textposition="top center", showlegend=False,marker=dict(5 unmodified linescustomdata=unique_entities[['label', 'score', 'frequency']],hovertemplate=("<b>%{text}</b><br>Label: %{customdata[0]}<br>Score: %{customdata[1]:.2f}<br>Frequency: %{customdata[2]}<extra></extra>")))legend_traces = []seen_labels = set()for index, row in unique_entities.iterrows():2 unmodified linesseen_labels.add(label)color = entity_color_map.get(label, '#cccccc')legend_traces.append(go.Scatter(x=[None], y=[None], mode='markers', marker=dict(size=10, color=color), name=f"{label.capitalize()}", showlegend=True))for trace in legend_traces:fig.add_trace(trace)fig.update_layout(title='Entity Co-occurrence Network (Edges = Same Sentence)',showlegend=True, hovermode='closest',3 unmodified linesmargin=dict(t=50, b=10, l=10, r=10), height=600)return fig# --- CSV GENERATION FUNCTION ---def generate_entity_csv(df):"""Generates a CSV file of the extracted entities in an in-memory buffer."""3 unmodified linescsv_buffer.seek(0)return csv_buffer# -----------------------------------# --- HTML REPORT GENERATION FUNCTION (MODIFIED FOR WHITE-LABEL) ---def generate_html_report(df, text_input, elapsed_time, df_topic_data, entity_color_map, report_title="Entity and Topic Analysis Report", branding_html=""):"""2 unmodified lines"""# Use the category values from the DataFrame to ensure the report matches the app's current mode (fixed or custom)unique_categories = df['category'].unique()# 1. Generate Visualizations (Plotly HTML)# 1a. Treemapfig_treemap = px.treemap(5 unmodified linescolor_discrete_sequence=px.colors.qualitative.Dark24)fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))treemap_html = fig_treemap.to_html(full_html=False, include_plotlyjs='cdn')# 1b. Pie Chartgrouped_counts = df['category'].value_counts().reset_index()grouped_counts.columns = ['Category', 'Count']color_seq = px.colors.qualitative.Pastel if len(grouped_counts) > 1 else px.colors.sequential.Cividisfig_pie = px.pie(grouped_counts, values='Count', names='Category',title='Distribution of Entities by Category',color_discrete_sequence=color_seq)fig_pie.update_layout(margin=dict(t=50, b=10))pie_html = fig_pie.to_html(full_html=False, include_plotlyjs='cdn')# 1c. Bar Chart (Category Count)fig_bar_category = px.bar(grouped_counts, x='Category', y='Count',color='Category', title='Total Entities per Category',color_discrete_sequence=color_seq)fig_bar_category.update_layout(xaxis={'categoryorder': 'total descending'},margin=dict(t=50, b=100))bar_category_html = fig_bar_category.to_html(full_html=False,include_plotlyjs='cdn')# 1d. Bar Chart (Most Frequent Entities)word_counts = df['text'].value_counts().reset_index()word_counts.columns = ['Entity', 'Count']3 unmodified linesfig_bar_freq = px.bar(repeating_entities, x='Entity', y='Count',color='Entity', title='Top 10 Most Frequent Entities',color_discrete_sequence=px.colors.sequential.Viridis)fig_bar_freq.update_layout(xaxis={'categoryorder': 'total descending'},margin=dict(t=50, b=100))bar_freq_html = fig_bar_freq.to_html(full_html=False, include_plotlyjs='cdn')# 1e. Network Graph HTML - IMPORTANT: Pass color mapnetwork_fig = generate_network_graph(df, text_input, entity_color_map)network_html = network_fig.to_html(full_html=False, include_plotlyjs='cdn')# 1f. Topic Charts HTMLtopic_charts_html = '<h3>Topic Word Weights (Bubble Chart)</h3>'if df_topic_data is not None and not df_topic_data.empty:bubble_figure = create_topic_word_bubbles(df_topic_data)6 unmodified linestopic_charts_html += '<p><strong>Topic Modeling requires more unique input.</strong></p>'topic_charts_html += '<p>Please enter text containing at least two unique entities to generate the Topic Bubble Chart.</p>'topic_charts_html += '</div>'# 2. Get Highlighted Text - IMPORTANT: Pass color maphighlighted_text_html = highlight_entities(text_input, df, entity_color_map).replace("div style", "div class='highlighted-text' style")# 3. Entity Tables (Pandas to HTML)entity_table_html = df[['text', 'label', 'score', 'start', 'end', 'category']].to_html(classes='table table-striped',index=False)# 4. Construct the Final HTML (UPDATED FOR WHITE-LABELING)html_content = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">18 unmodified lines<div class="container"><h1>{report_title}</h1><div class="metadata">{branding_html} <!-- CUSTOM BRANDING INSERTED HERE --><p><strong>Generated on:</strong> {time.strftime('%Y-%m-%d')}</p><p><strong>Processing Time:</strong> {elapsed_time:.2f} seconds</p></div><h2>1. Analyzed Text & Extracted Entities</h2>21 unmodified lines</html>"""return html_content# -----------------------------------# --- CHUNKING IMPLEMENTATION FOR LARGE TEXT ---def chunk_text(text, max_chunk_size=1500):"""Splits text into chunks by sentence/paragraph, respecting a max size (by character count)."""2 unmodified lineschunks = []current_chunk = ""current_offset = 0for segment in segments:if not segment: continueif len(current_chunk) + len(segment) > max_chunk_size and current_chunk:# Save the current chunk and its starting offsetchunks.append((current_chunk, current_offset))3 unmodified linescurrent_chunk += segmentif current_chunk:chunks.append((current_chunk, current_offset))return chunksdef process_chunked_text(text, labels, model):"""Processes large text in chunks and aggregates/offsets the entities."""# GLiNER model context size can be around 1024-1500 tokens/words. We use a generous char limit.# The word count limit is 10000, but we chunk around 500 words for safety/performance.MAX_CHUNK_CHARS = 3500chunks = chunk_text(text, max_chunk_size=MAX_CHUNK_CHARS)all_entities = []for chunk_text, chunk_offset in chunks:# Predict entities on the small chunkchunk_entities = model.predict_entities(chunk_text, labels)# Offset the start and end indices to match the original documentfor entity in chunk_entities:entity['start'] += chunk_offsetentity['end'] += chunk_offsetall_entities.append(entity)return all_entities# -----------------------------------# --- Page Configuration and Styling (No Sidebar) ---st.set_page_config(layout="wide", page_title="NER & Topic Report App")# --- Conditional Mobile Warning ---st.markdown("""7 unmodified lines[data-testid="stAppViewBlock"] {background-color: #ffffff !important;}/* CSS Media Query: Only show the content inside this selector when the screen width is 600px or less (typical mobile size) */@media (max-width: 600px) {#mobile-warning-container {36 unmodified lines</div>""",unsafe_allow_html=True)# ----------------------------------st.subheader("Entity and Topic Analysis Report Generator", divider="blue") # Changed divider from "rainbow" (often includes red/pink) to "blue"# Removed st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary") for white-labelingtab1, tab2 = st.tabs(["Embed", "Important Notes"])with tab1:with st.expander("Embed"):7 unmodified lines></iframe>'''st.code(code, language="html")with tab2:expander = st.expander("**Important Notes**")expander.markdown("""**Named Entities (Fixed Mode):** This DataHarvest web app predicts nine (9) labels: "person", "country", "city", "organization", "date", "time", "cardinal", "money", "position".**Custom Labels Mode:** You can define your own comma-separated labels (e.g., `product, symptom, client_id`) in the input box below.**Results:** Results are compiled into a single, comprehensive **HTML report** and a **CSV file** for easy download and sharing.**How to Use:** Type or paste your text into the text area below, then click the 'Results' button.""")st.markdown("For any errors or inquiries, please contact us at [info@your-company.com](mailto:info@your-company.com)") # Updated contact info# --- Comet ML Setup (Placeholder/Conditional) ---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)# --- Model Loading ---@st.cache_resourcedef load_ner_model(labels):"""Loads the GLiNER model and caches it."""try:1 unmodified linereturn GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)except Exception as e:# Log the actual error to the console for debuggingprint(f"FATAL ERROR: Failed to load NER model: {e}")st.error(f"Failed to load NER model. This may be due to a dependency issue or resource limits: {e}")st.stop()# --- LONG DEFAULT TEXT (178 Words) ---DEFAULT_TEXT = ("In June 2024, the founder, Dr. Emily Carter, officially announced a new, expansive partnership between "11 unmodified lines"are closely monitoring the impact on TechSolutions Inc.'s Q3 financial reports, expected to be released to the ""general public by October 1st. The goal is to deploy the **Astra** v2 platform before the next solar eclipse event in 2026.")# -----------------------------------# --- Session State Initialization (CRITICAL FIX) ---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 = ""40 unmodified lineswith col_clear:st.button("Clear text", on_click=clear_text, use_container_width=True)# --- Results Trigger and Processing (Updated Logic with Chunking) ---if run_button:# 1. Determine Active Labels and Modecustom_labels_raw = st.session_state.custom_labels_input8 unmodified lineselse:st.session_state.active_labels_list = custom_labels_listst.session_state.is_custom_mode = Trueelse:st.session_state.active_labels_list = FIXED_LABELSst.session_state.is_custom_mode = False10 unmodified lines# Define a safe threshold for when to start chunking (e.g., above 500 words)CHUNKING_THRESHOLD = 500should_chunk = word_count > CHUNKING_THRESHOLDmode_msg = f"{'custom' if st.session_state.is_custom_mode else 'fixed'} labels"if should_chunk:mode_msg += " with **chunking** for large text"with st.spinner(f"Extracting entities using {mode_msg}...", show_time=True):# Re-run prediction only if text or active labels have changedcurrent_settings = (text, tuple(active_labels))last_settings = (st.session_state.last_text, tuple(st.session_state.get('last_active_labels', [])))if current_settings != last_settings:st.session_state.last_text = textst.session_state['last_active_labels'] = active_labelsstart_time = time.time()# Load model using the determined active labelsmodel = load_ner_model(active_labels)# --- Model Prediction & Dataframe Creation (Using Chunking if needed) ---if should_chunk:entities = process_chunked_text(text, active_labels, model)st.info(f"Text was split into {len(chunk_text(text))} chunks for processing.")else:# Original logic for small textsentities = model.predict_entities(text, active_labels)elapsed_time = time.time() - start_timest.session_state.elapsed_time = elapsed_time# --- DataFrame Construction ---df = pd.DataFrame(entities)if df.empty:st.session_state.results_df = dfst.session_state.topic_results = Nonest.session_state.show_results = Trueelse:# Clean up entity text (optional, but good practice)df['text'] = df['text'].apply(remove_trailing_punctuation)# Map entities to categoriesif st.session_state.is_custom_mode:# For custom labels, group everything under a single categorydf['category'] = "User Defined Entities"else:# For fixed labels, use the fixed mappingdf['category'] = df['label'].map(REVERSE_FIXED_CATEGORY_MAPPING).fillna('Other')# Remove duplicates for topics/frequency analysis, keeping the highest scoredf_unique_entities = df.sort_values('score', ascending=False).drop_duplicates(subset=['text', 'label'])# --- Topic Modeling ---# We use the unique entities as input for the topic modelingdf_topic_data = perform_topic_modeling(df_unique_entities, num_topics=min(3, len(df_unique_entities.text.unique())), num_top_words=10)# Update session statest.session_state.results_df = dfst.session_state.topic_results = df_topic_datast.session_state.show_results = Trueelse:# If settings haven't changed, just show the last resultsst.session_state.show_results = True# --- Display Download Link and Results (Updated with White-Label inputs) ---if st.session_state.show_results:df = st.session_state.results_dfdf_topic_data = st.session_state.topic_results# Generate the color map based on the results DF labelscurrent_labels_in_df = df['label'].unique().tolist()entity_color_map = get_dynamic_color_map(current_labels_in_df, FIXED_ENTITY_COLOR_MAP)2 unmodified linesst.warning("No entities were found in the provided text with the current label set.")else:st.subheader("Analysis Results", divider="blue")# 1. Highlighted Textst.markdown(f"### 1. Analyzed Text with Highlighted Entities ({'Custom Mode' if st.session_state.is_custom_mode else 'Fixed Mode'})")st.markdown(highlight_entities(st.session_state.last_text, df, entity_color_map), unsafe_allow_html=True)# 2. Detailed Entity Analysis Tabsst.markdown("### 2. Detailed Entity Analysis")tab_category_details, tab_treemap_viz = st.tabs(["π Entities Grouped by Category", "πΊοΈ Treemap Distribution"])# Determine which categories to use for the tabsif st.session_state.is_custom_mode:unique_categories = ["User Defined Entities"]1 unmodified linest.markdown(f"**Custom Labels Detected: {', '.join(tabs_to_show)}**")else:unique_categories = list(FIXED_CATEGORY_MAPPING.keys())# --- Section 2a: Detailed Tables by Category/Label ---with tab_category_details:st.markdown("#### Detailed Entities Table (Grouped by Category)")if st.session_state.is_custom_mode:# In custom mode, group by the actual label since the category is just "User Defined Entities"tabs_list = df['label'].unique().tolist()22 unmodified lines)else:st.info(f"No entities of category **{category}** were found in the text.")# --- INSERTED GLOSSARY HERE ---with st.expander("See Glossary of tags"):st.write('''- **text**: ['entity extracted from your text data']- **label**: ['label (tag) assigned to a given extracted entity (custom or fixed)']- **category**: ['the grouping category (e.g., "Locations" or "User Defined Entities")']- **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']- **start**: ['index of the start of the corresponding entity']- **end**: ['index of the end of the corresponding entity']''')# --- END GLOSSARY INSERTION ---# --- Section 2b: Treemap Visualization ---with tab_treemap_viz:st.markdown("#### Treemap: Entity Distribution")6 unmodified lines)fig_treemap.update_layout(margin=dict(t=10, l=10, r=10, b=10))st.plotly_chart(fig_treemap, use_container_width=True)# --- Section 3: Comparative Charts (COMPLETED) ---st.markdown("---")st.markdown("### 3. Comparative Charts")col1, col2, col3 = st.columns(3)grouped_counts = df['category'].value_counts().reset_index()grouped_counts.columns = ['Category', 'Count']# Determine color sequence for chartschart_color_seq = px.colors.qualitative.Pastel if len(grouped_counts) > 1 else px.colors.sequential.Cividiswith col1: # Pie Chartfig_pie = px.pie(grouped_counts, values='Count', names='Category',title='Distribution of Entities by Category',color_discrete_sequence=chart_color_seq)fig_pie.update_layout(margin=dict(t=30, b=10, l=10, r=10), height=350)st.plotly_chart(fig_pie, use_container_width=True)with col2: # Bar Chart by Categoryst.markdown("#### Entity Count by Category")fig_bar_category = px.bar(grouped_counts, x='Category', y='Count', color='Category', title='Total Entities per Category', color_discrete_sequence=chart_color_seq)fig_bar_category.update_layout(margin=dict(t=30, b=10, l=10, r=10), height=350, showlegend=False)st.plotly_chart(fig_bar_category, use_container_width=True)with col3: # Bar Chart for Most Frequent Entitiesst.markdown("#### Top 10 Most Frequent Entities")word_counts = df['text'].value_counts().reset_index()5 unmodified linesst.plotly_chart(fig_bar_freq, use_container_width=True)else:st.info("No entities were repeated enough for a Top 10 frequency chart.")# 4. Network Graph and Topic Modelingst.markdown("---")st.markdown("### 4. Advanced Analysis")col_network, col_topic = st.columns(2)with col_network:with st.expander("π Entity Co-occurrence Network Graph", expanded=True):st.plotly_chart(generate_network_graph(df, st.session_state.last_text, entity_color_map), use_container_width=True)with col_topic:with st.expander("π‘ Topic Modeling (LDA)", expanded=True):if df_topic_data is not None and not df_topic_data.empty:st.plotly_chart(create_topic_word_bubbles(df_topic_data), use_container_width=True)st.markdown("This chart visualizes the key words driving the identified topics, based on extracted entities.")else:st.info("Topic Modeling requires at least two unique entities with a minimum frequency to perform statistical analysis.")# --- 5. White-Label Configuration (NEW SECTION FOR CUSTOM BRANDING) ---st.markdown("---")st.markdown("### 5. White-Label Report Configuration π¨")# Set a dynamic default title based on the modedefault_report_title = f"{'Custom' if st.session_state.is_custom_mode else 'Fixed'} Entity Analysis Report"custom_report_title = st.text_input("Type Your Report Title (for HTML Report), and then press Enter.",value=default_report_title)# UPDATED: Simplified input for the usercustom_branding_text_input = st.text_area("Type Your Brand Name or Tagline (Appears below the title in the report), and then press Enter.",1 unmodified linekey='custom_branding_input',help="Enter your brand name or a short tagline. This text will be automatically styled and included below the main title.")# 6. Downloads (Updated to pass custom variables)st.markdown("---")st.markdown("### 6. Downloads")col_csv, col_html = st.columns(2)# CSV Downloadcsv_buffer = generate_entity_csv(df)with col_csv:4 unmodified linesmime="text/csv",use_container_width=True)# --- NEW LOGIC: Wrap the simple text input into proper HTML for the report ---# We wrap the user's plain text in a styled HTML paragraph elementbranding_to_pass = f'<p style="font-size: 1.1em; font-weight: 500;">{custom_branding_text_input}</p>'# HTML Download (Passing custom white-label parameters)html_content = generate_html_report(df,12 unmodified linesfile_name="ner_topic_full_report.html",mime="text/html",use_container_width=True)21 unmodified lines2223242526273 unmodified lines31323334353637387 unmodified lines4647484950511 unmodified line535455565758596061626364656667689 unmodified lines7879808182838 unmodified lines92939495969798991002 unmodified lines1031041051061071081 unmodified line1101111121131141151161171181191201211221231241251261271281291301311321331 unmodified line13513613713813914014114214314414514614714817 unmodified lines1661671681691701711 unmodified line17317417517617717816 unmodified lines1951961971981992001 unmodified line2022032042052062072082092105 unmodified lines2162172182192202212 unmodified lines2242252262272282292302313 unmodified lines2352362372382392403 unmodified lines2442452462472482492 unmodified lines2522532542552562575 unmodified lines2632642652662672682692702712722732742752762772782793 unmodified lines2832842852862872882892902912926 unmodified lines29930030130230330430530630730830931031118 unmodified lines33033133233333433533621 unmodified lines3583593603613623632 unmodified lines3663673683693703713723733 unmodified lines3773783793803813823833843853863873883893903913923933943953963973983994004014027 unmodified lines41041141241341441536 unmodified lines4524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824837 unmodified lines4914924934944954964974984995005015025035045051 unmodified line5075085095105115125131 unmodified line51551651751851952052152252311 unmodified lines53553653753853954040 unmodified lines5815825835845855865878 unmodified lines59659759859960060110 unmodified lines6126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836842 unmodified lines6876886896906916926936946956966976981 unmodified line70070170270370470570670770822 unmodified lines7317327337347357367377387397406 unmodified lines7477487497507517527537547557567577587597607617627637647657667677687695 unmodified lines7757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088091 unmodified line8118128138148158168178188198204 unmodified lines82582682782882983083183283312 unmodified lines84684784884921 unmodified lines# ------------------------------from gliner import GLiNERfrom streamlit_extras.stylable_container import stylable_container# Using a try/except for comet_ml importtry:from comet_ml import Experiment3 unmodified linesdef log_parameter(self, *args): passdef log_table(self, *args): passdef end(self): pass# --- Model Home Directory (Fix for deployment environments) ---os.environ['HF_HOME'] = '/tmp'# --- Fixed Label Definitions and Mappings (Used as Fallback) ---FIXED_LABELS = ["person", "country", "city", "organization", "date", "time", "cardinal", "money", "position"]FIXED_ENTITY_COLOR_MAP = {7 unmodified lines"money": "#f43f5e", # Red"position": "#a855f7", # Violet}# --- Fixed Category Mapping ---FIXED_CATEGORY_MAPPING = {"People & Roles": ["person", "organization", "position"],1 unmodified line"Time & Dates": ["date", "time"],"Numbers & Finance": ["money", "cardinal"]}REVERSE_FIXED_CATEGORY_MAPPING = {label: category for category, label_list in FIXED_CATEGORY_MAPPING.items() for label in label_list}# --- Dynamic Color Generator for Custom Labels ---# Use Plotly's Alphabet set for a large pool of distinct colorsCOLOR_PALETTE = cycle(px.colors.qualitative.Alphabet)def extract_label(node_name):"""Extracts the label from a node string like 'Text (Label)'."""match = re.search(r'\(([^)]+)\)$', node_name)return match.group(1) if match else "Unknown"def remove_trailing_punctuation(text_string):"""Removes trailing punctuation from a string."""return text_string.rstrip(string.punctuation)def get_dynamic_color_map(active_labels, fixed_map):"""Generates a color map, using fixed colors if available, otherwise dynamic colors."""color_map = {}9 unmodified lines# Generate a new color from the palettecolor_map[label] = next(COLOR_PALETTE)return color_mapdef highlight_entities(text, df_entities, entity_color_map):"""Generates HTML to display text with entities highlighted and colored.8 unmodified lines# Ensure the entity indices are within the bounds of the full textstart = max(0, entity['start'])end = min(len(text), entity['end'])# Get entity text from the full document based on its indices# The 'text' column in the dataframe is now an attribute of the chunked text, not the original spanentity_text_from_full_doc = text[start:end]label = entity['label']color = entity_color_map.get(label, '#000000')# Create a span with background color and tooltip2 unmodified lineshighlighted_text = highlighted_text[:start] + highlight_html + highlighted_text[end:]# Use a div to mimic the Streamlit input box style for the reportreturn f'<div style="border: 1px solid #888888; padding: 15px; border-radius: 5px; background-color: #ffffff; font-family: monospace; white-space: pre-wrap; margin-bottom: 20px;">{highlighted_text}</div>'def perform_topic_modeling(df_entities, num_topics=2, num_top_words=10):"""Performs basic Topic Modeling using LDA."""documents = df_entities['text'].unique().tolist()1 unmodified line# but here we use the extracted entity texts as per the original code's intent.if len(documents) < 2:return NoneN = min(num_top_words, len(documents))try:tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, stop_words='english', ngram_range=(1, 3))tfidf = tfidf_vectorizer.fit_transform(documents)tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()if len(tfidf_feature_names) < num_topics:tfidf_vectorizer = TfidfVectorizer(max_df=1.0, min_df=1, stop_words='english', ngram_range=(1, 3))tfidf = tfidf_vectorizer.fit_transform(documents)tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()if len(tfidf_feature_names) < num_topics:return Nonelda = LatentDirichletAllocation(n_components=num_topics, max_iter=5, learning_method='online', random_state=42, n_jobs=-1)lda.fit(tfidf)topic_data_list = []for topic_idx, topic in enumerate(lda.components_):top_words_indices = topic.argsort()[:-N - 1:-1]top_words = [tfidf_feature_names[i] for i in top_words_indices]word_weights = [topic[i] for i in top_words_indices]for word, weight in zip(top_words, word_weights):topic_data_list.append({'Topic_ID': f'Topic #{topic_idx + 1}',1 unmodified line'Weight': weight,})return pd.DataFrame(topic_data_list)except Exception as e:return Nonedef create_topic_word_bubbles(df_topic_data):"""Generates a Plotly Bubble Chart for top words across all topics."""df_topic_data = df_topic_data.rename(columns={'Topic_ID': 'topic','Word': 'word', 'Weight': 'weight'})df_topic_data['x_pos'] = df_topic_data.indexif df_topic_data.empty:return Nonefig = px.scatter(df_topic_data,x='x_pos', y='weight', size='weight', color='topic', text='word', hover_name='word', size_max=40,17 unmodified linesmarker=dict(line=dict(width=1, color='DarkSlateGrey')))return figdef generate_network_graph(df, raw_text, entity_color_map):"""Generates a network graph visualization (Node Plot) with edges based on entity co-occurrence in sentences."""entity_counts = df['text'].value_counts().reset_index()1 unmodified lineunique_entities = df.drop_duplicates(subset=['text', 'label']).merge(entity_counts, on='text')if unique_entities.shape[0] < 2:return go.Figure().update_layout(title="Not enough unique entities for a meaningful graph.")num_nodes = len(unique_entities)thetas = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False)radius = 1016 unmodified linesnode2 = unique_entities_in_sentence[j]edge_tuple = tuple(sorted((node1, node2)))edges.add(edge_tuple)edge_x = []edge_y = []for edge in edges:1 unmodified lineif n1 in pos_map and n2 in pos_map:edge_x.extend([pos_map[n1]['x'], pos_map[n2]['x'], None])edge_y.extend([pos_map[n1]['y'], pos_map[n2]['y'], None])fig = go.Figure()edge_trace = go.Scatter(x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines', name='Co-occurrence Edges', showlegend=False)fig.add_trace(edge_trace)fig.add_trace(go.Scatter(x=unique_entities['x'], y=unique_entities['y'], mode='markers+text', name='Entities', text=unique_entities['text'], textposition="top center", showlegend=False,marker=dict(5 unmodified linescustomdata=unique_entities[['label', 'score', 'frequency']],hovertemplate=("<b>%{text}</b><br>Label: %{customdata[0]}<br>Score: %{customdata[1]:.2f}<br>Frequency: %{customdata[2]}<extra></extra>")))legend_traces = []seen_labels = set()for index, row in unique_entities.iterrows():2 unmodified linesseen_labels.add(label)color = entity_color_map.get(label, '#cccccc')legend_traces.append(go.Scatter(x=[None], y=[None], mode='markers', marker=dict(size=10, color=color), name=f"{label.capitalize()}", showlegend=True))for trace in legend_traces:fig.add_trace(trace)fig.update_layout(title='Entity Co-occurrence Network (Edges = Same Sentence)',showlegend=True, hovermode='closest',3 unmodified linesmargin=dict(t=50, b=10, l=10, r=10), height=600)return fig# --- CSV GENERATION FUNCTION ---def generate_entity_csv(df):"""Generates a CSV file of the extracted entities in an in-memory buffer."""3 unmodified linescsv_buffer.seek(0)return csv_buffer# -----------------------------------# --- HTML REPORT GENERATION FUNCTION (MODIFIED FOR WHITE-LABEL) ---def generate_html_report(df, text_input, elapsed_time, df_topic_data, entity_color_map, report_title="Entity and Topic Analysis Report", branding_html=""):"""2 unmodified lines"""# Use the category values from the DataFrame to ensure the report matches the app's current mode (fixed or custom)unique_categories = df['category'].unique()# 1. Generate Visualizations (Plotly HTML)# 1a. Treemapfig_treemap = px.treemap(5 unmodified linescolor_discrete_sequence=px.colors.qualitative.Dark24)fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))treemap_html = fig_treemap.to_html(full_html=False, include_plotlyjs='cdn') # 1b. Pie Chartgrouped_counts = df['category'].value_counts().reset_index()grouped_counts.columns = ['Category', 'Count']color_seq = px.colors.qualitative.Pastel if len(grouped_counts) > 1 else px.colors.sequential.Cividisfig_pie = px.pie(grouped_counts, values='Count', names='Category',title='Distribution of Entities by Category',color_discrete_sequence=color_seq)fig_pie.update_layout(margin=dict(t=50, b=10))pie_html = fig_pie.to_html(full_html=False, include_plotlyjs='cdn')# 1c. Bar Chart (Category Count)fig_bar_category = px.bar(grouped_counts, x='Category', y='Count',color='Category', title='Total Entities per Category',color_discrete_sequence=color_seq)fig_bar_category.update_layout(xaxis={'categoryorder': 'total descending'},margin=dict(t=50, b=100))bar_category_html = fig_bar_category.to_html(full_html=False,include_plotlyjs='cdn')# 1d. Bar Chart (Most Frequent Entities)word_counts = df['text'].value_counts().reset_index()word_counts.columns = ['Entity', 'Count']3 unmodified linesfig_bar_freq = px.bar(repeating_entities, x='Entity', y='Count',color='Entity', title='Top 10 Most Frequent Entities',color_discrete_sequence=px.colors.sequential.Viridis)fig_bar_freq.update_layout(xaxis={'categoryorder': 'total descending'},margin=dict(t=50, b=100))bar_freq_html = fig_bar_freq.to_html(full_html=False, include_plotlyjs='cdn')# 1e. Network Graph HTML - IMPORTANT: Pass color mapnetwork_fig = generate_network_graph(df, text_input, entity_color_map)network_html = network_fig.to_html(full_html=False, include_plotlyjs='cdn')# 1f. Topic Charts HTMLtopic_charts_html = '<h3>Topic Word Weights (Bubble Chart)</h3>'if df_topic_data is not None and not df_topic_data.empty:bubble_figure = create_topic_word_bubbles(df_topic_data)6 unmodified linestopic_charts_html += '<p><strong>Topic Modeling requires more unique input.</strong></p>'topic_charts_html += '<p>Please enter text containing at least two unique entities to generate the Topic Bubble Chart.</p>'topic_charts_html += '</div>'# 2. Get Highlighted Text - IMPORTANT: Pass color maphighlighted_text_html = highlight_entities(text_input, df, entity_color_map).replace("div style", "div class='highlighted-text' style")# 3. Entity Tables (Pandas to HTML)entity_table_html = df[['text', 'label', 'score', 'start', 'end', 'category']].to_html(classes='table table-striped',index=False)# 4. Construct the Final HTML (UPDATED FOR WHITE-LABELING)html_content = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">18 unmodified lines<div class="container"><h1>{report_title}</h1><div class="metadata">{branding_html} <p><strong>Generated on:</strong> {time.strftime('%Y-%m-%d')}</p><p><strong>Processing Time:</strong> {elapsed_time:.2f} seconds</p></div><h2>1. Analyzed Text & Extracted Entities</h2>21 unmodified lines</html>"""return html_content# --- CHUNKING IMPLEMENTATION FOR LARGE TEXT ---def chunk_text(text, max_chunk_size=1500):"""Splits text into chunks by sentence/paragraph, respecting a max size (by character count)."""2 unmodified lineschunks = []current_chunk = ""current_offset = 0for segment in segments:if not segment: continueif len(current_chunk) + len(segment) > max_chunk_size and current_chunk:# Save the current chunk and its starting offsetchunks.append((current_chunk, current_offset))3 unmodified linescurrent_chunk += segmentif current_chunk:chunks.append((current_chunk, current_offset))return chunksdef process_chunked_text(text, labels, model):"""Processes large text in chunks and aggregates/offsets the entities."""# GLiNER model context size can be around 1024-1500 tokens/words. We use a generous char limit.# The word count limit is 10000, but we chunk around 500 words for safety/performance.MAX_CHUNK_CHARS = 3500chunks = chunk_text(text, max_chunk_size=MAX_CHUNK_CHARS)all_entities = []for chunk_text, chunk_offset in chunks:# Predict entities on the small chunkchunk_entities = model.predict_entities(chunk_text, labels)# Offset the start and end indices to match the original documentfor entity in chunk_entities:entity['start'] += chunk_offsetentity['end'] += chunk_offsetall_entities.append(entity)return all_entities# -----------------------------------# --- Page Configuration and Styling (No Sidebar) ---st.set_page_config(layout="wide", page_title="NER & Topic Report App")# --- Conditional Mobile Warning ---st.markdown("""7 unmodified lines[data-testid="stAppViewBlock"] {background-color: #ffffff !important;}/* CSS Media Query: Only show the content inside this selector when the screen width is 600px or less (typical mobile size) */@media (max-width: 600px) {#mobile-warning-container {36 unmodified lines</div>""",unsafe_allow_html=True)# --- Sidebar Inputs for Topic Modeling (NEW) ---st.sidebar.header("Topic Modeling Settings π‘")num_topics_input = st.sidebar.slider("Number of Topics",min_value=2,max_value=10,value=5,step=1,key='num_topics_slider',help="The number of underlying topics (clusters) to discover in the entity data (LDA).")num_top_words_input = st.sidebar.slider("Number of Top Words per Topic",min_value=5,max_value=20,value=10,step=1,key='num_top_words_slider',help="The number of most important words to display for each topic.")st.sidebar.markdown("---")# -----------------------------------------------st.subheader("Entity and Topic Analysis Report Generator", divider="blue") # Changed divider from "rainbow" (often includes red/pink) to "blue"# Removed st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary") for white-labelingtab1, tab2 = st.tabs(["Embed", "Important Notes"])with tab1:with st.expander("Embed"):7 unmodified lines></iframe>'''st.code(code, language="html")with tab2:expander = st.expander("**Important Notes**")expander.markdown("""**Named Entities (Fixed Mode):** This DataHarvest web app predicts nine (9) labels: "person", "country", "city", "organization", "date", "time", "cardinal", "money", "position".**Custom Labels Mode:** You can define your own comma-separated labels (e.g., `product, symptom, client_id`) in the input box below.**Results:** Results are compiled into a single, comprehensive **HTML report** and a **CSV file** for easy download and sharing.**How to Use:** Type or paste your text into the text area below, then click the 'Results' button.""")st.markdown("For any errors or inquiries, please contact us at [info@your-company.com](mailto:info@your-company.com)") # Updated contact info# --- Comet ML Setup (Placeholder/Conditional) ---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)# --- Model Loading ---@st.cache_resourceddef load_ner_model(labels):"""Loads the GLiNER model and caches it."""try:1 unmodified linereturn GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)except Exception as e:# Log the actual error to the console for debuggingprint(f"FATAL ERROR: Failed to load NER model: {e}")st.error(f"Failed to load NER model. This may be due to a dependency issue or resource limits: {e}")st.stop()# --- LONG DEFAULT TEXT (178 Words) ---DEFAULT_TEXT = ("In June 2024, the founder, Dr. Emily Carter, officially announced a new, expansive partnership between "11 unmodified lines"are closely monitoring the impact on TechSolutions Inc.'s Q3 financial reports, expected to be released to the ""general public by October 1st. The goal is to deploy the **Astra** v2 platform before the next solar eclipse event in 2026.")# -----------------------------------# --- Session State Initialization (CRITICAL FIX) ---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 = ""40 unmodified lineswith col_clear:st.button("Clear text", on_click=clear_text, use_container_width=True)# --- Results Trigger and Processing (Completed Logic with Chunking and Topic Vars) ---if run_button:# 1. Determine Active Labels and Modecustom_labels_raw = st.session_state.custom_labels_input8 unmodified lineselse:st.session_state.active_labels_list = custom_labels_listst.session_state.is_custom_mode = Trueelse:st.session_state.active_labels_list = FIXED_LABELSst.session_state.is_custom_mode = False10 unmodified lines# Define a safe threshold for when to start chunking (e.g., above 500 words)CHUNKING_THRESHOLD = 500should_chunk = word_count > CHUNKING_THRESHOLDmode_msg = f"{'custom' if st.session_state.is_custom_mode else 'fixed'} labels"if should_chunk:mode_msg += " with **chunking** for large text"# --- Topic Modeling Input Retrieval ---# Get the current slider valuescurrent_num_topics = st.session_state.num_topics_slidercurrent_num_top_words = st.session_state.num_top_words_sliderwith st.spinner(f"Extracting entities using {mode_msg}...", show_time=True):# Re-run prediction only if text, active labels, OR topic parameters have changedcurrent_settings = (text, tuple(active_labels), current_num_topics, current_num_top_words)# Add topic settings to last_settings checklast_settings = (st.session_state.last_text,tuple(st.session_state.get('last_active_labels', [])),st.session_state.get('last_num_topics', None),st.session_state.get('last_num_top_words', None))if current_settings != last_settings:start_time = time.time()ner_model = load_ner_model(labels=active_labels)# 2. Perform NER Extractionif should_chunk:all_entities_list = process_chunked_text(text, active_labels, ner_model)else:all_entities_list = ner_model.predict_entities(text, active_labels)df = pd.DataFrame(all_entities_list)if df.empty:df_topic_data = Noneelse:# 3. Add Category Mappingdf['category'] = df['label'].apply(lambda l: REVERSE_FIXED_CATEGORY_MAPPING.get(l, "User Defined Entities"))# 4. Perform Topic Modeling (Passing the new parameters)df_topic_data = perform_topic_modeling(df_entities=df,num_topics=current_num_topics, # NEW PARAMETERnum_top_words=current_num_top_words # NEW PARAMETER)end_time = time.time()elapsed_time = end_time - start_time# 5. Save Results to Session Statest.session_state.results_df = dfst.session_state.topic_results = df_topic_datast.session_state.elapsed_time = elapsed_timest.session_state.last_text = textst.session_state.show_results = Truest.session_state.last_active_labels = active_labelsst.session_state.last_num_topics = current_num_topics # Save topic settingsst.session_state.last_num_top_words = current_num_top_words # Save topic settingselse:st.info("Results already calculated for the current text and settings.")st.session_state.show_results = True# --- Display Download Link and Results (Updated with White-Label inputs) ---if st.session_state.show_results:df = st.session_state.results_dfdf_topic_data = st.session_state.topic_results# Generate the color map based on the results DF labelscurrent_labels_in_df = df['label'].unique().tolist()entity_color_map = get_dynamic_color_map(current_labels_in_df, FIXED_ENTITY_COLOR_MAP)2 unmodified linesst.warning("No entities were found in the provided text with the current label set.")else:st.subheader("Analysis Results", divider="blue")# 1. Highlighted Textst.markdown(f"### 1. Analyzed Text with Highlighted Entities ({'Custom Mode' if st.session_state.is_custom_mode else 'Fixed Mode'})")st.markdown(highlight_entities(st.session_state.last_text, df, entity_color_map), unsafe_allow_html=True)# 2. Detailed Entity Analysis Tabsst.markdown("### 2. Detailed Entity Analysis")tab_category_details, tab_treemap_viz = st.tabs(["π Entities Grouped by Category", "πΊοΈ Treemap Distribution"])# Determine which categories to use for the tabsif st.session_state.is_custom_mode:unique_categories = ["User Defined Entities"]1 unmodified linest.markdown(f"**Custom Labels Detected: {', '.join(tabs_to_show)}**")else:unique_categories = list(FIXED_CATEGORY_MAPPING.keys())# --- Section 2a: Detailed Tables by Category/Label ---with tab_category_details:st.markdown("#### Detailed Entities Table (Grouped by Category)")if st.session_state.is_custom_mode:# In custom mode, group by the actual label since the category is just "User Defined Entities"tabs_list = df['label'].unique().tolist()22 unmodified lines)else:st.info(f"No entities of category **{category}** were found in the text.")# --- INSERTED GLOSSARY HERE ---with st.expander("See Glossary of tags"):st.write('''- **text**: ['entity extracted from your text data']- **label**: ['label (tag) assigned to a given extracted entity (custom or fixed)']- **category**: ['the grouping category (e.g., "Locations" or "User Defined Entities")']- **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']- **start**: ['index of the start of the corresponding entity']- **end**: ['index of the end of the corresponding entity']''')# --- END GLOSSARY INSERTION ---# --- Section 2b: Treemap Visualization ---with tab_treemap_viz:st.markdown("#### Treemap: Entity Distribution")6 unmodified lines)fig_treemap.update_layout(margin=dict(t=10, l=10, r=10, b=10))st.plotly_chart(fig_treemap, use_container_width=True)# --- Section 3: Comparative Charts (COMPLETED) ---st.markdown("---")st.markdown("### 3. Comparative Charts")col1, col2, col3 = st.columns(3)grouped_counts = df['category'].value_counts().reset_index()grouped_counts.columns = ['Category', 'Count']# Determine color sequence for chartschart_color_seq = px.colors.qualitative.Pastel if len(grouped_counts) > 1 else px.colors.sequential.Cividiswith col1: # Pie Chartfig_pie = px.pie(grouped_counts, values='Count', names='Category',title='Distribution of Entities by Category',color_discrete_sequence=chart_color_seq)fig_pie.update_layout(margin=dict(t=30, b=10, l=10, r=10), height=350)st.plotly_chart(fig_pie, use_container_width=True)with col2: # Bar Chart by Categoryst.markdown("#### Entity Count by Category")fig_bar_category = px.bar(grouped_counts, x='Category', y='Count', color='Category', title='Total Entities per Category', color_discrete_sequence=chart_color_seq)fig_bar_category.update_layout(margin=dict(t=30, b=10, l=10, r=10), height=350, showlegend=False)st.plotly_chart(fig_bar_category, use_container_width=True)with col3: # Bar Chart for Most Frequent Entitiesst.markdown("#### Top 10 Most Frequent Entities")word_counts = df['text'].value_counts().reset_index()5 unmodified linesst.plotly_chart(fig_bar_freq, use_container_width=True)else:st.info("No entities were repeated enough for a Top 10 frequency chart.")# 4. Network Graph and Topic Modelingst.markdown("---")st.markdown("### 4. Advanced Analysis")col_network, col_topic = st.columns(2)with col_network:with st.expander("π Entity Co-occurrence Network Graph", expanded=True):st.plotly_chart(generate_network_graph(df, st.session_state.last_text, entity_color_map), use_container_width=True)with col_topic:with st.expander("π‘ Topic Modeling (LDA)", expanded=True):# Display the current settings used for the topic modeling resultst.markdown(f"""**LDA Parameters:*** Topics: **{st.session_state.last_num_topics}*** Top Words: **{st.session_state.last_num_top_words}**""")if df_topic_data is not None and not df_topic_data.empty:st.plotly_chart(create_topic_word_bubbles(df_topic_data), use_container_width=True)st.markdown("This chart visualizes the key words driving the identified topics, based on extracted entities.")else:st.info("Topic Modeling requires at least two unique entities with a minimum frequency to perform statistical analysis.")# --- 5. White-Label Configuration (NEW SECTION FOR CUSTOM BRANDING) ---st.markdown("---")st.markdown("### 5. White-Label Report Configuration π¨")# Set a dynamic default title based on the modedefault_report_title = f"{'Custom' if st.session_state.is_custom_mode else 'Fixed'} Entity Analysis Report"custom_report_title = st.text_input("Type Your Report Title (for HTML Report), and then press Enter.",value=default_report_title)# UPDATED: Simplified input for the usercustom_branding_text_input = st.text_area("Type Your Brand Name or Tagline (Appears below the title in the report), and then press Enter.",1 unmodified linekey='custom_branding_input',help="Enter your brand name or a short tagline. This text will be automatically styled and included below the main title.")# 6. Downloads (Updated to pass custom variables)st.markdown("---")st.markdown("### 6. Downloads")col_csv, col_html = st.columns(2)# CSV Downloadcsv_buffer = generate_entity_csv(df)with col_csv:4 unmodified linesmime="text/csv",use_container_width=True)# --- NEW LOGIC: Wrap the simple text input into proper HTML for the report ---# We wrap the user's plain text in a styled HTML paragraph elementbranding_to_pass = f'<p style="font-size: 1.1em; font-weight: 500;">{custom_branding_text_input}</p>'# HTML Download (Passing custom white-label parameters)html_content = generate_html_report(df,12 unmodified linesfile_name="ner_topic_full_report.html",mime="text/html",use_container_width=True)
src/streamlit_app.py+82-143