AIEcosystem commited on
Commit
beafc64
ยท
verified ยท
1 Parent(s): 3d9a101

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +766 -58
src/streamlit_app.py CHANGED
@@ -1,66 +1,774 @@
 
 
 
1
  import streamlit as st
2
- import plotly.express as px
3
  import pandas as pd
 
 
 
 
 
 
 
 
4
  from io import BytesIO
5
- from pptx import Presentation
6
- from pptx.util import Inches
7
-
8
- # Sample data and Plotly graph
9
- df = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Value': [10, 20, 30]})
10
- fig = px.bar(df, x='Category', y='Value', title='Sample Plotly Bar Chart')
11
-
12
- # Convert Plotly figure to image
13
- img_buffer = BytesIO()
14
- fig.write_image(img_buffer, format='png', width=800, height=400)
15
- img_buffer.seek(0)
16
- img_data = img_buffer.getvalue()
17
-
18
- # Function to create PPTX
19
- def create_presentation():
20
- prs = Presentation()
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Title slide
23
- slide = prs.slides.add_slide(prs.slide_layouts[0])
24
- title = slide.shapes.title
25
- title.text = "Streamlit Plotly Export"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Slide with Plotly image and table
28
- slide = prs.slides.add_slide(prs.slide_layouts[1])
29
- title = slide.shapes.title
30
- title.text = "Plotly Chart and Data"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- # Add Plotly image
33
- left = Inches(1)
34
- top = Inches(1.5)
35
- slide.shapes.add_picture(BytesIO(img_data), left, top, width=Inches(6))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- # Add table
38
- rows, cols = df.shape
39
- left = Inches(1)
40
- top = Inches(4)
41
- width = Inches(6)
42
- height = Inches(0.8)
43
- table = slide.shapes.add_table(rows + 1, cols, left, top, width, height).table
44
- table.cell(0, 0).text = 'Category'
45
- table.cell(0, 1).text = 'Value'
46
- for i in range(rows):
47
- table.cell(i + 1, 0).text = df.iloc[i]['Category']
48
- table.cell(i + 1, 1).text = str(df.iloc[i]['Value'])
49
 
50
- # Save to bytes
51
- bio = BytesIO()
52
- prs.save(bio)
53
- bio.seek(0)
54
- return bio.getvalue()
55
-
56
- # Streamlit UI
57
- st.title("Export Plotly Graph to PPTX")
58
- st.plotly_chart(fig) # Display the Plotly chart
59
- if st.button("Generate and Download Slides"):
60
- pptx_data = create_presentation()
61
- st.download_button(
62
- label="Download PPTX",
63
- data=pptx_data,
64
- file_name="plotly_slides.pptx",
65
- mime="application/vnd.openxmlformats-officedocument.presentationml.presentation"
66
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ['HF_HOME'] = '/tmp'
3
+ import time
4
  import streamlit as st
5
+ import streamlit.components.v1 as components
6
  import pandas as pd
7
+ import io
8
+ import plotly.express as px
9
+ import plotly.graph_objects as go
10
+ import numpy as np
11
+ import re
12
+ import string
13
+ import json
14
+ # --- Imports for file generation (no pptx) ---
15
  from io import BytesIO
16
+ import plotly.io as pio
17
+ # ---------------------------
18
+ # --- Stable Scikit-learn LDA Imports ---
19
+ from sklearn.feature_extraction.text import TfidfVectorizer
20
+ from sklearn.decomposition import LatentDirichletAllocation
21
+ # ------------------------------
22
+ from gliner import GLiNER
23
+ from streamlit_extras.stylable_container import stylable_container
24
+
25
+ # Using a try/except for comet_ml import
26
+ try:
27
+ from comet_ml import Experiment
28
+ except ImportError:
29
+ class Experiment:
30
+ def __init__(self, **kwargs): pass
31
+ def log_parameter(self, *args): pass
32
+ def log_table(self, *args): pass
33
+ def end(self): pass
34
+
35
+ # --- Model Home Directory (Fix for deployment environments) ---
36
+ # Set HF_HOME environment variable to a writable path
37
+ os.environ['HF_HOME'] = '/tmp'
38
+
39
+ # --- Color Map for Highlighting and Network Graph Nodes (NO PINK COLORS) ---
40
+ entity_color_map = {
41
+ "person": "#10b981",
42
+ "country": "#3b82f6",
43
+ "city": "#4ade80",
44
 
45
+ "organization": "#f59e0b",
46
+ "date": "#8b5cf6",
47
+ "time": "#ec4899",
48
+ "cardinal": "#06b6d4",
49
+ "money": "#f43f5e",
50
+ "position": "#a855f7",
51
+
52
+ }
53
+
54
+ # --- Label Definitions and Category Mapping (Used by the App) ---
55
+ labels = list(entity_color_map.keys())
56
+
57
+
58
+
59
+
60
+ labels = ["person", "country", "city", "organization", "date", "time", "cardinal", "money", "position"]
61
+ category_mapping = {
62
+ "People": ["person", "organization", "position"],
63
+ "Locations": ["country", "city"],
64
+ "Time": ["date", "time"],
65
+ "Numbers": ["money", "cardinal"]
66
+ }
67
+
68
+
69
+
70
+
71
+
72
+
73
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
74
+
75
+
76
+ # --- Utility Functions for Analysis and Plotly ---
77
+ def extract_label(node_name):
78
+ """Extracts the label from a node string like 'Text (Label)'."""
79
+ match = re.search(r'\(([^)]+)\)$', node_name)
80
+ return match.group(1) if match else "Unknown"
81
+
82
+ def remove_trailing_punctuation(text_string):
83
+ """Removes trailing punctuation from a string."""
84
+ return text_string.rstrip(string.punctuation)
85
+
86
+ def highlight_entities(text, df_entities):
87
+ """Generates HTML to display text with entities highlighted and colored."""
88
+ if df_entities.empty:
89
+ return text
90
+
91
+ # Sort entities by start index descending to insert highlights without affecting subsequent indices
92
+ entities = df_entities.sort_values(by='start', ascending=False).to_dict('records')
93
+ highlighted_text = text
94
+
95
+ for entity in entities:
96
+ start = entity['start']
97
+ end = entity['end']
98
+ label = entity['label']
99
+ entity_text = entity['text']
100
+ color = entity_color_map.get(label, '#000000')
101
+
102
+ # Create a span with background color and tooltip
103
+ highlight_html = f'<span style="background-color: {color}; color: white; padding: 2px 4px; border-radius: 3px; cursor: help;" title="{label}">{entity_text}</span>'
104
+ # Replace the original text segment with the highlighted HTML
105
+ highlighted_text = highlighted_text[:start] + highlight_html + highlighted_text[end:]
106
+
107
+ # Use a div to mimic the Streamlit input box style for the report
108
+ return f'<div style="border: 1px solid #CCCCCC; padding: 15px; border-radius: 5px; background-color: #FFFFFF; font-family: monospace; white-space: pre-wrap; margin-bottom: 20px;">{highlighted_text}</div>'
109
+
110
+ def perform_topic_modeling(df_entities, num_topics=2, num_top_words=10):
111
+ """
112
+ Performs basic Topic Modeling using LDA on the extracted entities
113
+ and returns structured data for visualization.
114
+ """
115
+ documents = df_entities['text'].unique().tolist()
116
+ if len(documents) < 2:
117
+ return None
118
+
119
+ N = min(num_top_words, len(documents))
120
+ try:
121
+ tfidf_vectorizer = TfidfVectorizer(
122
+ max_df=0.95,
123
+ min_df=1,
124
+ stop_words='english'
125
+ )
126
+ tfidf = tfidf_vectorizer.fit_transform(documents)
127
+ tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()
128
+
129
+ lda = LatentDirichletAllocation(
130
+ n_components=num_topics, max_iter=5, learning_method='online',random_state=42, n_jobs=-1
131
+ )
132
+ lda.fit(tfidf)
133
+ topic_data_list = []
134
+ for topic_idx, topic in enumerate(lda.components_):
135
+ top_words_indices = topic.argsort()[:-N - 1:-1]
136
+ top_words = [tfidf_feature_names[i] for i in top_words_indices]
137
+ word_weights = [topic[i] for i in top_words_indices]
138
+ for word, weight in zip(top_words, word_weights):
139
+ topic_data_list.append({
140
+ 'Topic_ID': f'Topic #{topic_idx + 1}',
141
+ 'Word': word,
142
+ 'Weight': weight,
143
+ })
144
+ return pd.DataFrame(topic_data_list)
145
+ except Exception as e:
146
+ st.error(f"Topic modeling failed: {e}")
147
+ return None
148
+
149
+ def create_topic_word_bubbles(df_topic_data):
150
+ """Generates a Plotly Bubble Chart for top words across all topics."""
151
+ # Renaming columns to match the output of perform_topic_modeling
152
+ df_topic_data = df_topic_data.rename(columns={'Topic_ID': 'topic', 'Word': 'word', 'Weight': 'weight'})
153
+ df_topic_data['x_pos'] = df_topic_data.index # Use index for x-position in the app
154
+
155
+ if df_topic_data.empty:
156
+ return None
157
+ fig = px.scatter(
158
+ df_topic_data,
159
+ x='x_pos',
160
+ y='weight',
161
+ size='weight',
162
+ color='topic',
163
+ hover_name='word',
164
+ size_max=80,
165
+ title='Topic Word Weights (Bubble Chart)',
166
+ color_discrete_sequence=px.colors.qualitative.Bold,
167
+ labels={
168
+ 'x_pos': 'Entity/Word Index',
169
+ 'weight': 'Word Weight',
170
+ 'topic': 'Topic ID'
171
+ },
172
+ custom_data=['word', 'weight', 'topic']
173
+ )
174
+ fig.update_layout(
175
+ xaxis_title="Entity/Word (Bubble size = Word Weight)",
176
+ yaxis_title="Word Weight",
177
+ xaxis={'tickangle': -45, 'showgrid': False},
178
+ yaxis={'showgrid': True},
179
+ showlegend=True,
180
+ plot_bgcolor='#FFFFFF', # Removed pink
181
+ paper_bgcolor='#FFFFFF', # Removed pink
182
+ height=600,
183
+ margin=dict(t=50, b=100, l=50, r=10),
184
+ )
185
+ fig.update_traces(hovertemplate='<b>%{customdata[0]}</b><br>Weight: %{customdata[1]:.3f}<extra></extra>',
186
+ marker=dict(line=dict(width=1, color='DarkSlateGrey')))
187
+ return fig
188
+
189
+ def generate_network_graph(df, raw_text):
190
+ """
191
+ Generates a network graph visualization (Node Plot) with edges
192
+ based on entity co-occurrence in sentences.
193
+ """
194
+ entity_counts = df['text'].value_counts().reset_index()
195
+ entity_counts.columns = ['text', 'frequency']
196
+
197
+ unique_entities = df.drop_duplicates(subset=['text', 'label']).merge(entity_counts, on='text')
198
+ if unique_entities.shape[0] < 2:
199
+ return go.Figure().update_layout(title="Not enough unique entities for a meaningful graph.")
200
+
201
+ num_nodes = len(unique_entities)
202
+ thetas = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False)
203
+
204
+ radius = 10
205
+ unique_entities['x'] = radius * np.cos(thetas) + np.random.normal(0, 0.5, num_nodes)
206
+ unique_entities['y'] = radius * np.sin(thetas) + np.random.normal(0, 0.5, num_nodes)
207
+
208
+ pos_map = unique_entities.set_index('text')[['x', 'y']].to_dict('index')
209
+ edges = set()
210
+
211
+ sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\!)\s', raw_text)
212
+ for sentence in sentences:
213
+ entities_in_sentence = []
214
+ for entity_text in unique_entities['text'].unique():
215
+ if entity_text.lower() in sentence.lower():
216
+ entities_in_sentence.append(entity_text)
217
+ unique_entities_in_sentence = list(set(entities_in_sentence))
218
+
219
+ for i in range(len(unique_entities_in_sentence)):
220
+ for j in range(i + 1, len(unique_entities_in_sentence)):
221
+ node1 = unique_entities_in_sentence[i]
222
+ node2 = unique_entities_in_sentence[j]
223
+ edge_tuple = tuple(sorted((node1, node2)))
224
+ edges.add(edge_tuple)
225
+
226
+ edge_x = []
227
+ edge_y = []
228
+
229
+ for edge in edges:
230
+ n1, n2 = edge
231
+ if n1 in pos_map and n2 in pos_map:
232
+ edge_x.extend([pos_map[n1]['x'], pos_map[n2]['x'], None])
233
+ edge_y.extend([pos_map[n1]['y'], pos_map[n2]['y'], None])
234
+
235
+ fig = go.Figure()
236
+
237
+ edge_trace = go.Scatter(
238
+ x=edge_x, y=edge_y,
239
+ line=dict(width=0.5, color='#888'),
240
+ hoverinfo='none',
241
+ mode='lines',
242
+ name='Co-occurrence Edges',
243
+ showlegend=False
244
+ )
245
+ fig.add_trace(edge_trace)
246
+
247
+ fig.add_trace(go.Scatter(
248
+ x=unique_entities['x'],
249
+ y=unique_entities['y'],
250
+ mode='markers+text',
251
+ name='Entities',
252
+ text=unique_entities['text'],
253
+ textposition="top center",
254
+ showlegend=False,
255
+ marker=dict(
256
+ size=unique_entities['frequency'] * 5 + 10,
257
+ color=[entity_color_map.get(label, '#cccccc') for label in unique_entities['label']],
258
+ line_width=1,
259
+ line_color='black',
260
+ opacity=0.9
261
+ ),
262
+ textfont=dict(size=10),
263
+ customdata=unique_entities[['label', 'score', 'frequency']],
264
+ hovertemplate=(
265
+ "<b>%{text}</b><br>" +
266
+ "Label: %{customdata[0]}<br>" +
267
+ "Score: %{customdata[1]:.2f}<br>" +
268
+ "Frequency: %{customdata[2]}<extra></extra>"
269
+ )
270
+ ))
271
+
272
+ legend_traces = []
273
+ seen_labels = set()
274
+ for index, row in unique_entities.iterrows():
275
+ label = row['label']
276
+ if label not in seen_labels:
277
+ seen_labels.add(label)
278
+ color = entity_color_map.get(label, '#cccccc')
279
+ legend_traces.append(go.Scatter(
280
+ x=[None], y=[None], mode='markers', marker=dict(size=10, color=color),
281
+ name=f"{label.capitalize()}", showlegend=True
282
+ ))
283
+ for trace in legend_traces:
284
+ fig.add_trace(trace)
285
+
286
+ fig.update_layout(
287
+ title='Entity Co-occurrence Network (Edges = Same Sentence)',
288
+ showlegend=True,
289
+ hovermode='closest',
290
+ xaxis=dict(showgrid=False, zeroline=False, showticklabels=False, range=[-15, 15]),
291
+ yaxis=dict(showgrid=False, zeroline=False, showticklabels=False, range=[-15, 15]),
292
+ plot_bgcolor='#f9f9f9',
293
+ paper_bgcolor='#f9f9f9',
294
+ margin=dict(t=50, b=10, l=10, r=10),
295
+ height=600
296
+ )
297
+
298
+ return fig
299
+
300
+
301
+ # --- NEW CSV GENERATION FUNCTION ---
302
+ def generate_entity_csv(df):
303
+ """
304
+ Generates a CSV file of the extracted entities in an in-memory buffer,
305
+ including text, label, category, score, start, and end indices.
306
+ """
307
+ csv_buffer = BytesIO()
308
+ # Select desired columns and write to buffer
309
+ df_export = df[['text', 'label', 'category', 'score', 'start', 'end']]
310
+ csv_buffer.write(df_export.to_csv(index=False).encode('utf-8'))
311
+ csv_buffer.seek(0)
312
+ return csv_buffer
313
+ # -----------------------------------
314
+
315
+ # --- Existing App Functionality (HTML) ---
316
+ # NOTE: Removed the 'grouped_entity_table_html' generation that counted by label,
317
+ # keeping only the grouped by category table generation if needed for the HTML report,
318
+ # but prioritizing the Streamlit display of the grouped-by-category table.
319
+
320
+ def generate_html_report(df, text_input, elapsed_time, df_topic_data):
321
+ """
322
+ Generates a full HTML report containing all analysis results and
323
+ visualizations. (Simplified HTML generation for brevity in code)
324
+ """
325
+ # ... (Plotly chart HTML generation code remains largely the same)
326
 
327
+ # 1. Generate Visualizations (Plotly HTML)
328
+
329
+ # 1a. Treemap
330
+ fig_treemap = px.treemap(
331
+ df,
332
+ path=[px.Constant("All Entities"), 'category', 'label', 'text'],
333
+ values='score',
334
+ color='category',
335
+ title="Entity Distribution by Category and Label",
336
+ color_discrete_sequence=px.colors.qualitative.Dark24
337
+ )
338
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
339
+ treemap_html = fig_treemap.to_html(full_html=False, include_plotlyjs='cdn')
340
+
341
+ # 1b. Pie Chart
342
+ grouped_counts = df['category'].value_counts().reset_index()
343
+ grouped_counts.columns = ['Category', 'Count']
344
+ fig_pie = px.pie(grouped_counts, values='Count', names='Category',title='Distribution of Entities by Category',color_discrete_sequence=px.colors.sequential.RdBu)
345
+ fig_pie.update_layout(margin=dict(t=50, b=10))
346
+ pie_html = fig_pie.to_html(full_html=False, include_plotlyjs='cdn')
347
+
348
+ # 1c. Bar Chart (Category Count)
349
+ fig_bar_category = px.bar(grouped_counts, x='Category', y='Count',color='Category', title='Total Entities per Category',color_discrete_sequence=px.colors.qualitative.Pastel)
350
+ fig_bar_category.update_layout(xaxis={'categoryorder': 'total descending'},margin=dict(t=50, b=100))
351
+ bar_category_html = fig_bar_category.to_html(full_html=False,include_plotlyjs='cdn')
352
+
353
+ # 1d. Bar Chart (Most Frequent Entities)
354
+ word_counts = df['text'].value_counts().reset_index()
355
+ word_counts.columns = ['Entity', 'Count']
356
+ repeating_entities = word_counts[word_counts['Count'] > 1].head(10)
357
+ bar_freq_html = '<p>No entities appear more than once in the text for visualization.</p>'
358
+
359
+ if not repeating_entities.empty:
360
+ fig_bar_freq = px.bar(repeating_entities, x='Entity', y='Count',color='Entity', title='Top 10 Most Frequent Entities',color_discrete_sequence=px.colors.sequential.Plasma)
361
+ fig_bar_freq.update_layout(xaxis={'categoryorder': 'total descending'},margin=dict(t=50, b=100))
362
+ bar_freq_html = fig_bar_freq.to_html(full_html=False, include_plotlyjs='cdn')
363
+
364
+ # 1e. Network Graph HTML
365
+ network_fig = generate_network_graph(df, text_input)
366
+ network_html = network_fig.to_html(full_html=False, include_plotlyjs='cdn')
367
+
368
+ # 1f. Topic Charts HTML
369
+ topic_charts_html = '<h3>Topic Word Weights (Bubble Chart)</h3>'
370
+ if df_topic_data is not None and not df_topic_data.empty:
371
+ bubble_figure = create_topic_word_bubbles(df_topic_data)
372
+ if bubble_figure:
373
+ topic_charts_html += f'<div class="chart-box">{bubble_figure.to_html(full_html=False, include_plotlyjs="cdn")}</div>'
374
+ else:
375
+ topic_charts_html += '<p style="color: red;">Error: Topic modeling data was available but visualization failed.</p>'
376
+ else:
377
+ topic_charts_html += '<div class="chart-box" style="text-align: center; padding: 50px; background-color: #fff; border: 1px dashed #cccccc;">'
378
+ topic_charts_html += '<p><strong>Topic Modeling requires more unique input.</strong></p>'
379
+ topic_charts_html += '<p>Please enter text containing at least two unique entities to generate the Topic Bubble Chart.</p>'
380
+ topic_charts_html += '</div>'
381
+
382
+ # 2. Get Highlighted Text
383
+ highlighted_text_html = highlight_entities(text_input, df).replace("div style", "div class='highlighted-text' style")
384
+
385
+ # 3. Entity Tables (Pandas to HTML)
386
+ # The grouped by category table is used here for the HTML export
387
+ grouped_entity_table_df = df.groupby(['category', 'label']).size().reset_index(name='Count')
388
+ grouped_entity_table_df.columns = ['Category', 'Entity', 'Count'] # Column Renaming
389
+ grouped_entity_table_html = grouped_entity_table_df.to_html(
390
+ classes='table table-striped',
391
+ index=False
392
+ )
393
 
394
+ # 4. Construct the Final HTML
395
+ html_content = f"""<!DOCTYPE html><html lang="en"><head>
396
+ <meta charset="UTF-8">
397
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
398
+ <title>Entity and Topic Analysis Report</title>
399
+ <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
400
+ <style>
401
+ body {{ font-family: 'Inter', sans-serif; margin: 0; padding: 20px; background-color: #f4f4f9; color: #333; }}
402
+ .container {{ max-width: 1200px; margin: 0 auto; background-color: #ffffff; padding: 30px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }}
403
+ h1 {{ color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; margin-top: 0; }}
404
+ h2 {{ color: #007bff; margin-top: 30px; border-bottom: 1px solid #ddd; padding-bottom: 5px; }}
405
+ h3 {{ color: #555; margin-top: 20px; }}
406
+ .metadata {{ background-color: #e6f7ff; padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 0.9em; }}
407
+ .chart-box {{ background-color: #f9f9f9; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); min-width: 0; margin-bottom: 20px; }}
408
+ table {{ width: 100%; border-collapse: collapse; margin-top: 15px; }}
409
+ table th, table td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
410
+ table th {{ background-color: #f0f0f0; }}
411
+ .highlighted-text {{ border: 1px solid #CCCCCC; padding: 15px; border-radius: 5px; background-color: #FFFFFF; font-family: monospace; white-space: pre-wrap; margin-bottom: 20px; }}
412
+ </style></head><body>
413
+ <div class="container">
414
+ <h1>Entity and Topic Analysis Report</h1>
415
+ <div class="metadata">
416
+ <p><strong>Generated At:</strong> {time.strftime('%Y-%m-%d %H:%M:%S')}</p>
417
+ <p><strong>Processing Time:</strong> {elapsed_time:.2f} seconds</p>
418
+ </div>
419
+ <h2>1. Analyzed Text & Extracted Entities</h2>
420
+ <h3>Original Text with Highlighted Entities</h3>
421
+ <div class="highlighted-text-container">
422
+ {highlighted_text_html}
423
+ </div>
424
+ <h2>2. Entities Count by Category and Entity</h2>
425
+ {grouped_entity_table_html}
426
+ <h2>3. Data Visualizations</h2>
427
+ <h3>3.1 Entity Distribution Treemap</h3>
428
+ <div class="chart-box">{treemap_html}</div>
429
+ <h3>3.2 Comparative Charts</h3>
430
+ <div class="chart-box">{pie_html}</div>
431
+ <div class="chart-box">{bar_category_html}</div>
432
+ <div class="chart-box">{bar_freq_html}</div>
433
+ <h3>3.3 Entity Relationship Map</h3>
434
+ <div class="chart-box">{network_html}</div>
435
+ <h2>4. Topic Modeling</h2>
436
+ {topic_charts_html}
437
+ </div></body></html>
438
+ """
439
+ return html_content
440
+
441
+
442
+ # --- Page Configuration and Styling (No Sidebar, Removed Pink) ---
443
+ st.set_page_config(layout="wide", page_title="NER & Topic Report App")
444
+ st.markdown(
445
+ """
446
+ <style>
447
+ /* Overall app container - NO SIDEBAR */
448
+ .main {
449
+ background-color: #f0f2f6; /* Light Grey/Default */
450
+ color: #333333; /* Dark grey text for contrast */
451
+ }
452
+ .stApp {
453
+ background-color: #f0f2f6;
454
+ }
455
+ /* Text Area background and text color (input fields) */
456
+ .stTextArea textarea {
457
+ background-color: #FFFFFF; /* White for input fields */
458
+ color: #000000; /* Black text for input */
459
+ border: 1px solid #CCCCCC; /* Neutral border */
460
+ }
461
+ /* Button styling */
462
+ .stButton > button {
463
+ background-color: #007bff; /* Blue for the button */
464
+ color: #FFFFFF; /* White text for contrast */
465
+ border: none;
466
+ padding: 10px 20px;
467
+ border-radius: 5px;
468
+ }
469
+ /* Expander header and content background */
470
+ .streamlit-expanderHeader, .streamlit-expanderContent {
471
+ background-color: #e6f7ff; /* Very Light Blue/Neutral */
472
+ color: #333333;
473
+ }
474
+ </style>
475
+ """,
476
+ unsafe_allow_html=True)
477
+ st.subheader("NER and Topic Analysis Report Generator", divider="blue")
478
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="secondary")
479
+ expander = st.expander("**Important notes**")
480
+ expander.write(f"""**Named Entities:** This app predicts fifteen (15) labels: {', '.join(entity_color_map.keys())}.
481
+ **Dependencies:** Note that **image export** requires the Python libraries `plotly` and `kaleido`.
482
+
483
+ **How to Use:** Type or paste your text into the text area below, then press Ctrl + Enter. Click the 'Results' button to extract entities and generate the report.""")
484
+
485
+ expander = st.expander("**Important notes**")
486
+ expander.write("""**Named Entities:** This DataHarvest web app predicts nine (9) labels: "person", "country", "city", "organization", "date", "time", "cardinal", "money", "position"
487
+
488
+ **Results:** Results are compiled into a single, comprehensive **HTML report** and a **CSV file** for easy download and sharing.
489
+
490
+ **How to Use:** Type or paste your text (max. 1000 words) into the text area below, press Ctrl + Enter, and then click the 'Results' button.
491
+
492
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.""")
493
+
494
+
495
+
496
+
497
+ st.markdown("For any errors or inquiries, please contact us at [info@nlpblogs.com](mailto:info@nlpblogs.com)")
498
+
499
+ # --- Comet ML Setup (Placeholder/Conditional) ---
500
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
501
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
502
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
503
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
504
+
505
+ # --- Model Loading ---
506
+ @st.cache_resource
507
+ def load_ner_model():
508
+ """Loads the GLiNER model and caches it."""
509
+ try:
510
+ return GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)
511
+ except Exception as e:
512
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
513
+ st.stop()
514
+
515
+ model = load_ner_model()
516
+
517
+ # --- LONG DEFAULT TEXT (178 Words) ---
518
+ DEFAULT_TEXT = (
519
+ "In June 2024, the founder, Dr. Emily Carter, officially announced a new, expansive partnership between "
520
+ "TechSolutions Inc. and the European Space Agency (ESA). This strategic alliance represents a significant "
521
+ "leap forward for commercial space technology across the entire European Union. The agreement, finalized "
522
+ "on Monday in Paris, France, focuses specifically on jointly developing the next generation of the 'Astra' "
523
+ "software platform. This platform is critical for processing and managing the vast amounts of data being sent "
524
+ "back from the recent Mars rover mission. The core team, including lead engineer Marcus Davies, will hold "
525
+ "their first collaborative workshop in Berlin, Germany, on August 15th. The community response on social "
526
+ "media platform X (under the username @TechSolutionsCEO) was overwhelmingly positive, with many major tech "
527
+ "publications, including Wired Magazine, predicting a major impact on the space technology industry by the "
528
+ "end of the year. The platform is designed to be compatible with both Windows and Linux operating systems. "
529
+ "The initial funding, secured via a Series B round, totaled $50 million. Financial analysts from Morgan Stanley "
530
+ "are closely monitoring the impact on TechSolutions Inc.'s Q3 financial reports, expected to be released to the "
531
+ "general public by October 1st. The goal is to deploy the Astra v2 platform before the next solar eclipse event in 2026."
532
+ )
533
+ # -----------------------------------
534
+ # --- Session State Initialization (CRITICAL FIX) ---
535
+ if 'show_results' not in st.session_state:
536
+ st.session_state.show_results = False
537
+ if 'last_text' not in st.session_state:
538
+ st.session_state.last_text = ""
539
+ if 'results_df' not in st.session_state:
540
+ st.session_state.results_df = pd.DataFrame()
541
+ if 'elapsed_time' not in st.session_state:
542
+ st.session_state.elapsed_time = 0.0
543
+ if 'topic_results' not in st.session_state:
544
+ st.session_state.topic_results = None
545
+ if 'my_text_area' not in st.session_state:
546
+ st.session_state.my_text_area = DEFAULT_TEXT
547
+
548
+ # --- Clear Button Function (MODIFIED) ---
549
+ def clear_text():
550
+ """Clears the text area (sets it to an empty string) and hides results."""
551
+ st.session_state['my_text_area'] = ""
552
+ st.session_state.show_results = False
553
+ st.session_state.last_text = ""
554
+ st.session_state.results_df = pd.DataFrame()
555
+ st.session_state.elapsed_time = 0.0
556
+ st.session_state.topic_results = None
557
+
558
+ # --- Text Input and Clear Button ---
559
+ word_limit = 1000
560
+ text = st.text_area(
561
+ f"Type or paste your text below (max {word_limit} words), and then press Ctrl + Enter",
562
+ height=250,
563
+ key='my_text_area',
564
+ value=st.session_state.my_text_area)
565
+
566
+ word_count = len(text.split())
567
+ st.markdown(f"**Word count:** {word_count}/{word_limit}")
568
+ st.button("Clear text", on_click=clear_text)
569
+
570
+ # --- Results Trigger and Processing (Updated Logic) ---
571
+ if st.button("Results"):
572
+ if not text.strip():
573
+ st.warning("Please enter some text to extract entities.")
574
+ st.session_state.show_results = False
575
+ elif word_count > word_limit:
576
+ st.warning(f"Your text exceeds the {word_limit} word limit. Please shorten it to continue.")
577
+ st.session_state.show_results = False
578
+ else:
579
+ with st.spinner("Extracting entities and generating report data...", show_time=True):
580
+ if text != st.session_state.last_text:
581
+ st.session_state.last_text = text
582
+ start_time = time.time()
583
+
584
+ # --- Model Prediction & Dataframe Creation ---
585
+ entities = model.predict_entities(text, labels)
586
+ df = pd.DataFrame(entities)
587
+
588
+ if not df.empty:
589
+ df['text'] = df['text'].apply(remove_trailing_punctuation)
590
+ df['category'] = df['label'].map(reverse_category_mapping)
591
+ st.session_state.results_df = df
592
+
593
+ unique_entity_count = len(df['text'].unique())
594
+ N_TOP_WORDS_TO_USE = min(10, unique_entity_count)
595
+
596
+ st.session_state.topic_results = perform_topic_modeling(
597
+ df,
598
+ num_topics=2,
599
+ num_top_words=N_TOP_WORDS_TO_USE
600
+ )
601
+
602
+ if comet_initialized:
603
+ experiment = Experiment(api_key=COMET_API_KEY, workspace=COMET_WORKSPACE, project_name=COMET_PROJECT_NAME)
604
+ experiment.log_parameter("input_text", text)
605
+ experiment.log_table("predicted_entities", df)
606
+ experiment.end()
607
+ else:
608
+ st.session_state.results_df = pd.DataFrame()
609
+ st.session_state.topic_results = None
610
+
611
+ end_time = time.time()
612
+ st.session_state.elapsed_time = end_time - start_time
613
+
614
+ st.session_state.show_results = True
615
+
616
+ # --- Results Display ---
617
+ if st.session_state.show_results and not st.session_state.results_df.empty:
618
+ st.success(f"Processing complete in {st.session_state.elapsed_time:.2f} seconds! ๐ŸŽ‰")
619
+
620
+ df = st.session_state.results_df
621
+ text_input = st.session_state.last_text
622
+ elapsed_time = st.session_state.elapsed_time
623
+ df_topic_data = st.session_state.topic_results
624
 
625
+ # --- Highlighted Text and Download Buttons (Above Tabs) ---
626
+ st.subheader("1. Analyzed Text & Extracted Entities", divider="blue")
627
+ st.markdown(
628
+ highlight_entities(text_input, df),
629
+ unsafe_allow_html=True
630
+ )
631
+
632
+ st.subheader("Downloads", divider="blue")
633
+ col1, col2, col3 = st.columns([1, 1, 3])
 
 
 
634
 
635
+ # 1. Download CSV
636
+ csv_buffer = generate_entity_csv(df)
637
+ col1.download_button(
638
+ label="Download Entities as CSV",
639
+ data=csv_buffer.getvalue(),
640
+ file_name="ner_entities.csv",
641
+ mime="text/csv"
642
+ )
643
+
644
+ # 2. Download HTML Report
645
+ html_content = generate_html_report(df, text_input, elapsed_time, df_topic_data)
646
+ col2.download_button(
647
+ label="Download Full HTML Report",
648
+ data=html_content.encode('utf-8'),
649
+ file_name="ner_analysis_report.html",
650
+ mime="text/html"
651
+ )
652
+
653
+ st.markdown("---")
654
+
655
+ # --- Tabs Implementation ---
656
+ tab1, tab2 = st.tabs(["๐Ÿ“Š Entity Data (Table)", "๐Ÿ“ˆ Visualizations & Topics"])
657
+
658
+ with tab1:
659
+ # Create the summary table with the requested column name changes
660
+ grouped_entity_table = df.groupby(['category', 'label']).size().reset_index(name='Count')
661
+ grouped_entity_table.columns = ['Category', 'Entity', 'Count']
662
+
663
+ st.markdown("## Entity Counts by Category and Entity")
664
+ st.dataframe(grouped_entity_table.sort_values(by=['Category', 'Count'], ascending=[True, False]), use_container_width=True)
665
+ with st.expander("See Glossary of tags"):
666
+ st.write('''
667
+ - **start**: ['index of the start of the corresponding entity']
668
+ - **end**: ['index of the end of the corresponding entity']
669
+ - **text**: ['entity extracted from your text data']
670
+ - **label**: ['label (tag) assigned to a given extracted entity']
671
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
672
+
673
+ ''')
674
+
675
+
676
+ with tab2:
677
+ st.markdown("## Visualizations")
678
+
679
+ # 3a. Treemap (As requested in Tab 2)
680
+ fig_treemap = px.treemap(
681
+ df,
682
+ path=[px.Constant("All Entities"), 'category', 'label', 'text'],
683
+ values='score',
684
+ color='category',
685
+ title="Entity Distribution by Category and Label",
686
+ color_discrete_sequence=px.colors.qualitative.Dark24
687
+ )
688
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
689
+ st.markdown("### Entity Distribution Treemap")
690
+ st.plotly_chart(fig_treemap, use_container_width=True)
691
+
692
+ st.markdown("---")
693
+
694
+ # 3b. Pie Chart and Category Bar Chart side-by-side
695
+ col_pie, col_bar_cat = st.columns(2)
696
+
697
+ # Pie Chart
698
+ grouped_counts = df['category'].value_counts().reset_index()
699
+ grouped_counts.columns = ['Category', 'Count']
700
+ fig_pie = px.pie(grouped_counts, values='Count', names='Category',
701
+ title='Distribution of Entities by Category',
702
+ color_discrete_sequence=px.colors.sequential.RdBu)
703
+ fig_pie.update_layout(margin=dict(t=50, b=10))
704
+ with col_pie:
705
+ st.markdown("### Distribution of Entities by Category")
706
+ st.plotly_chart(fig_pie, use_container_width=True)
707
+
708
+ # Category Bar Chart
709
+ fig_bar_category = px.bar(grouped_counts, x='Category', y='Count',
710
+ color='Category', title='Total Entities per Category',
711
+ color_discrete_sequence=px.colors.qualitative.Pastel)
712
+ fig_bar_category.update_layout(xaxis={'categoryorder': 'total descending'}, margin=dict(t=50, b=10))
713
+ with col_bar_cat:
714
+ st.markdown("### Total Entities per Category")
715
+ st.plotly_chart(fig_bar_category, use_container_width=True)
716
+
717
+ st.markdown("---")
718
+
719
+ # 3c. Most Frequent Entities Bar Chart
720
+ word_counts = df['text'].value_counts().reset_index()
721
+ word_counts.columns = ['Entity', 'Count']
722
+ repeating_entities = word_counts[word_counts['Count'] > 1].head(10)
723
+
724
+ st.markdown("### Top 10 Most Frequent Entities")
725
+ if not repeating_entities.empty:
726
+ fig_bar_freq = px.bar(repeating_entities, x='Entity', y='Count',
727
+ color='Entity', title='Top 10 Most Frequent Entities',
728
+ color_discrete_sequence=px.colors.sequential.Plasma)
729
+ fig_bar_freq.update_layout(xaxis={'categoryorder': 'total descending'}, margin=dict(t=50, b=100))
730
+ st.plotly_chart(fig_bar_freq, use_container_width=True)
731
+ else:
732
+ st.info("No entities appear more than once in the text for visualization.")
733
+
734
+ st.markdown("---")
735
+
736
+ # 3d. Network Graph
737
+ st.markdown("### Entity Relationship Map")
738
+ network_fig = generate_network_graph(df, text_input)
739
+ st.plotly_chart(network_fig, use_container_width=True)
740
+
741
+ st.markdown("---")
742
+
743
+ # 4. Topic Modeling
744
+ st.markdown("## Topic Modeling")
745
+
746
+ if df_topic_data is not None and not df_topic_data.empty:
747
+ st.markdown("### Bubble size = word weight")
748
+ bubble_figure = create_topic_word_bubbles(df_topic_data)
749
+ st.plotly_chart(bubble_figure, use_container_width=True)
750
+
751
+ st.markdown("### Top Words by Topic")
752
+ # Simple table display for topic data
753
+ st.dataframe(df_topic_data, use_container_width=True)
754
+ else:
755
+ st.info("Topic Modeling requires more unique input (at least two unique entities) to be performed.")
756
+
757
+ elif st.session_state.show_results and st.session_state.results_df.empty:
758
+ st.warning("No entities were extracted from the provided text.")
759
+
760
+
761
+ st.write("Use the following code to embed the DataHarvest web app on your website. Feel free to adjust the width and height values to fit your page.")
762
+ code = '''
763
+ <iframe
764
+ src="https://aiecosystem-dataharvest.hf.space"
765
+ frameborder="0"
766
+ width="850"
767
+ height="450"
768
+ ></iframe>
769
+ '''
770
+ st.code(code, language="html")
771
+
772
+
773
+
774
+