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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
|
|
|
| 3 |
import streamlit as st
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
import re
|
| 7 |
+
import string
|
| 8 |
+
import json
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
|
| 11 |
+
# --- Visualization & PPTX ---
|
| 12 |
+
import plotly.express as px
|
| 13 |
+
import plotly.graph_objects as go
|
| 14 |
+
import plotly.io as pio
|
| 15 |
+
from pptx import Presentation
|
| 16 |
+
from pptx.util import Inches, Pt
|
| 17 |
+
|
| 18 |
+
# --- NLP & Analysis ---
|
| 19 |
+
from gliner import GLiNER
|
| 20 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 21 |
+
from sklearn.decomposition import LatentDirichletAllocation
|
| 22 |
+
|
| 23 |
+
# --- 1. CONFIGURATION & STYLING ---
|
| 24 |
+
os.environ['HF_HOME'] = '/tmp'
|
| 25 |
+
|
| 26 |
+
entity_color_map = {
|
| 27 |
+
"person": "#10b981", "country": "#3b82f6", "city": "#4ade80",
|
| 28 |
+
"organization": "#f59e0b", "date": "#8b5cf6", "time": "#ec4899",
|
| 29 |
+
"cardinal": "#06b6d4", "money": "#f43f5e", "position": "#a855f7"
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
labels = list(entity_color_map.keys())
|
| 33 |
+
category_mapping = {
|
| 34 |
+
"People": ["person", "organization", "position"],
|
| 35 |
+
"Locations": ["country", "city"],
|
| 36 |
+
"Time": ["date", "time"],
|
| 37 |
+
"Numbers": ["money", "cardinal"]
|
| 38 |
+
}
|
| 39 |
+
reverse_category_mapping = {label: cat for cat, lbls in category_mapping.items() for label in lbls}
|
| 40 |
+
|
| 41 |
+
# --- 2. CORE UTILITY FUNCTIONS ---
|
| 42 |
+
|
| 43 |
+
def remove_trailing_punctuation(text_string):
|
| 44 |
+
return text_string.rstrip(string.punctuation)
|
| 45 |
+
|
| 46 |
+
def highlight_entities(text, df_entities):
|
| 47 |
+
if df_entities.empty:
|
| 48 |
+
return text
|
| 49 |
+
# Sort entities by start index descending to prevent index shifting
|
| 50 |
+
entities = df_entities.sort_values(by='start', ascending=False).to_dict('records')
|
| 51 |
+
highlighted_text = text
|
| 52 |
+
for entity in entities:
|
| 53 |
+
start, end = entity['start'], entity['end']
|
| 54 |
+
label, entity_text = entity['label'], entity['text']
|
| 55 |
+
color = entity_color_map.get(label, '#000000')
|
| 56 |
+
highlight_html = f'<span style="background-color: {color}; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;">{entity_text}</span>'
|
| 57 |
+
highlighted_text = highlighted_text[:start] + highlight_html + highlighted_text[end:]
|
| 58 |
+
return f'<div class="highlighted-text" style="border: 1px solid #ddd; padding: 15px; border-radius: 8px; background-color: #ffffff; line-height: 2; white-space: pre-wrap;">{highlighted_text}</div>'
|
| 59 |
+
|
| 60 |
+
def perform_topic_modeling(df_entities, num_topics=2, num_top_words=10):
|
| 61 |
+
documents = df_entities['text'].unique().tolist()
|
| 62 |
+
if len(documents) < 2: return None
|
| 63 |
+
try:
|
| 64 |
+
tfidf_vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1, 3), min_df=1)
|
| 65 |
+
tfidf = tfidf_vectorizer.fit_transform(documents)
|
| 66 |
+
feature_names = tfidf_vectorizer.get_feature_names_out()
|
| 67 |
+
lda = LatentDirichletAllocation(n_components=num_topics, random_state=42)
|
| 68 |
+
lda.fit(tfidf)
|
| 69 |
+
|
| 70 |
+
topic_data = []
|
| 71 |
+
for idx, topic in enumerate(lda.components_):
|
| 72 |
+
top_indices = topic.argsort()[:-num_top_words - 1:-1]
|
| 73 |
+
for i in top_indices:
|
| 74 |
+
topic_data.append({'Topic_ID': f'Topic #{idx + 1}', 'Word': feature_names[i], 'Weight': topic[i]})
|
| 75 |
+
return pd.DataFrame(topic_data)
|
| 76 |
+
except: return None
|
| 77 |
+
|
| 78 |
+
# --- 3. VISUALIZATION FUNCTIONS (FIXED TITLES) ---
|
| 79 |
+
|
| 80 |
+
def create_topic_word_bubbles(df_topic_data):
|
| 81 |
+
df = df_topic_data.rename(columns={'Topic_ID': 'topic','Word': 'word', 'Weight': 'weight'})
|
| 82 |
+
df['x_pos'] = range(len(df))
|
| 83 |
+
fig = px.scatter(df, x='x_pos', y='weight', size='weight', color='topic', text='word', title='Topic Word Weights')
|
| 84 |
+
# FIX: Increased top margin for title visibility
|
| 85 |
+
fig.update_layout(margin=dict(t=80, b=50), xaxis_showticklabels=False, plot_bgcolor='#f9f9f9')
|
| 86 |
+
fig.update_traces(textposition='middle center', textfont=dict(color='white', size=10))
|
| 87 |
+
return fig
|
| 88 |
+
|
| 89 |
+
def generate_network_graph(df, raw_text):
|
| 90 |
+
counts = df['text'].value_counts().reset_index(name='frequency')
|
| 91 |
+
unique = df.drop_duplicates(subset=['text']).merge(counts, on='text')
|
| 92 |
+
num_nodes = len(unique)
|
| 93 |
+
thetas = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False)
|
| 94 |
+
unique['x'] = 10 * np.cos(thetas)
|
| 95 |
+
unique['y'] = 10 * np.sin(thetas)
|
| 96 |
+
|
| 97 |
+
fig = go.Figure()
|
| 98 |
+
fig.add_trace(go.Scatter(
|
| 99 |
+
x=unique['x'], y=unique['y'], mode='markers+text', text=unique['text'],
|
| 100 |
+
marker=dict(size=unique['frequency']*5 + 15, color=[entity_color_map.get(l, '#ccc') for l in unique['label']])
|
| 101 |
+
))
|
| 102 |
+
# FIX: Added top margin for Title
|
| 103 |
+
fig.update_layout(title="Entity Relationship Map", margin=dict(t=80), showlegend=False, xaxis_visible=False, yaxis_visible=False)
|
| 104 |
+
return fig
|
| 105 |
+
|
| 106 |
+
# --- 4. EXPORT FUNCTIONS ---
|
| 107 |
+
|
| 108 |
+
def generate_html_report(df, text_input, elapsed_time, df_topic_data):
|
| 109 |
+
# Prepare all charts with fixed layout margins
|
| 110 |
+
fig_tree = px.treemap(df, path=[px.Constant("All"), 'category', 'label', 'text'], values='score', title="Entity Hierarchy")
|
| 111 |
+
fig_tree.update_layout(margin=dict(t=60, b=20, l=20, r=20))
|
| 112 |
+
|
| 113 |
+
tree_html = fig_tree.to_html(full_html=False, include_plotlyjs='cdn')
|
| 114 |
+
net_html = generate_network_graph(df, text_input).to_html(full_html=False, include_plotlyjs='cdn')
|
| 115 |
+
|
| 116 |
+
html_template = f"""
|
| 117 |
+
<html>
|
| 118 |
+
<head>
|
| 119 |
+
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
|
| 120 |
+
<style>
|
| 121 |
+
body {{ font-family: sans-serif; background: #f4f7f6; padding: 30px; }}
|
| 122 |
+
.card {{ background: white; padding: 25px; border-radius: 12px; margin-bottom: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }}
|
| 123 |
+
/* FIX: Critical for title visibility */
|
| 124 |
+
.chart-box {{ min-height: 500px; overflow: visible !important; border: 1px solid #eee; }}
|
| 125 |
+
h1, h2 {{ color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }}
|
| 126 |
+
</style>
|
| 127 |
+
</head>
|
| 128 |
+
<body>
|
| 129 |
+
<div class="card">
|
| 130 |
+
<h1>NER & Topic Analysis Report</h1>
|
| 131 |
+
<p>Processing Time: {elapsed_time:.2f}s</p>
|
| 132 |
+
<h2>1. Highlighted Entities</h2>
|
| 133 |
+
{highlight_entities(text_input, df)}
|
| 134 |
+
<h2>2. Visual Analytics</h2>
|
| 135 |
+
<div class="chart-box">{tree_html}</div>
|
| 136 |
+
<div class="chart-box">{net_html}</div>
|
| 137 |
+
</div>
|
| 138 |
+
</body>
|
| 139 |
+
</html>
|
| 140 |
+
"""
|
| 141 |
+
return html_template
|
| 142 |
+
|
| 143 |
+
def generate_pptx_report(df):
|
| 144 |
+
prs = Presentation()
|
| 145 |
+
slide = prs.slides.add_slide(prs.slide_layouts[0])
|
| 146 |
+
slide.shapes.title.text = "Entity Analysis"
|
| 147 |
+
slide = prs.slides.add_slide(prs.slide_layouts[1])
|
| 148 |
+
slide.shapes.title.text = "Entity List"
|
| 149 |
+
tf = slide.placeholders[1].text_frame
|
| 150 |
+
for i, row in df.head(15).iterrows():
|
| 151 |
+
p = tf.add_paragraph()
|
| 152 |
+
p.text = f"{row['text']} ({row['label']})"
|
| 153 |
+
buffer = BytesIO()
|
| 154 |
+
prs.save(buffer)
|
| 155 |
+
buffer.seek(0)
|
| 156 |
+
return buffer
|
| 157 |
+
|
| 158 |
+
# --- 5. STREAMLIT UI & LOGIC ---
|
| 159 |
+
|
| 160 |
+
st.set_page_config(layout="wide", page_title="DataHarvest NER")
|
| 161 |
+
|
| 162 |
+
@st.cache_resource
|
| 163 |
+
def load_model():
|
| 164 |
+
return GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True)
|
| 165 |
+
|
| 166 |
+
model = load_model()
|
| 167 |
+
|
| 168 |
+
# Session State Init
|
| 169 |
+
if 'results_df' not in st.session_state:
|
| 170 |
+
st.session_state.results_df = pd.DataFrame()
|
| 171 |
+
st.session_state.show = False
|
| 172 |
+
|
| 173 |
+
st.subheader("Entity & Topic Analysis Report Generator", divider="blue")
|
| 174 |
+
|
| 175 |
+
text = st.text_area("Paste text here (max 1000 words):", height=250)
|
| 176 |
+
|
| 177 |
+
if st.button("Run Analysis"):
|
| 178 |
+
if text:
|
| 179 |
+
with st.spinner("Processing..."):
|
| 180 |
+
start = time.time()
|
| 181 |
+
entities = model.predict_entities(text, labels)
|
| 182 |
+
df = pd.DataFrame(entities)
|
| 183 |
+
if not df.empty:
|
| 184 |
+
df['text'] = df['text'].apply(remove_trailing_punctuation)
|
| 185 |
+
df['category'] = df['label'].map(reverse_category_mapping)
|
| 186 |
+
st.session_state.results_df = df
|
| 187 |
+
st.session_state.elapsed = time.time() - start
|
| 188 |
+
st.session_state.topics = perform_topic_modeling(df)
|
| 189 |
+
st.session_state.show = True
|
| 190 |
+
else:
|
| 191 |
+
st.warning("No entities found.")
|
| 192 |
+
|
| 193 |
+
if st.session_state.show:
|
| 194 |
+
df = st.session_state.results_df
|
| 195 |
+
|
| 196 |
+
st.markdown("### 1. Extracted Entities")
|
| 197 |
+
st.markdown(highlight_entities(text, df), unsafe_allow_html=True)
|
| 198 |
+
|
| 199 |
+
t1, t2, t3 = st.tabs(["Charts", "Network Map", "Topics"])
|
| 200 |
+
|
| 201 |
+
with t1:
|
| 202 |
+
fig_tree = px.treemap(df, path=['category', 'label', 'text'], values='score', title="Entity Treemap")
|
| 203 |
+
# Ensure the preview also has margins
|
| 204 |
+
fig_tree.update_layout(margin=dict(t=50))
|
| 205 |
+
st.plotly_chart(fig_tree, use_container_width=True)
|
| 206 |
+
|
| 207 |
+
with t2:
|
| 208 |
+
st.plotly_chart(generate_network_graph(df, text), use_container_width=True)
|
| 209 |
+
|
| 210 |
+
with t3:
|
| 211 |
+
if st.session_state.topics is not None:
|
| 212 |
+
st.plotly_chart(create_topic_word_bubbles(st.session_state.topics), use_container_width=True)
|
| 213 |
+
else:
|
| 214 |
+
st.info("Not enough data for topic modeling.")
|
| 215 |
|
| 216 |
+
st.divider()
|
| 217 |
+
st.markdown("### Download Artifacts")
|
| 218 |
+
c1, c2, c3 = st.columns(3)
|
| 219 |
+
|
| 220 |
+
with c1:
|
| 221 |
+
st.download_button("Download HTML Report",
|
| 222 |
+
generate_html_report(df, text, st.session_state.elapsed, st.session_state.topics),
|
| 223 |
+
"report.html", "text/html", type="primary")
|
| 224 |
+
with c2:
|
| 225 |
+
csv = df.to_csv(index=False).encode('utf-8')
|
| 226 |
+
st.download_button("Download CSV Data", csv, "entities.csv", "text/csv")
|
| 227 |
+
with c3:
|
| 228 |
+
st.download_button("Download PPTX Summary", generate_pptx_report(df), "summary.pptx")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|