File size: 12,797 Bytes
3b3ebed
 
 
 
 
 
 
 
 
 
 
 
 
09141b1
 
 
 
3b3ebed
 
 
 
 
 
 
 
09141b1
 
 
 
3b3ebed
 
 
 
 
 
 
09141b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b3ebed
 
 
 
 
 
 
 
09141b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b3ebed
 
 
 
 
 
 
09141b1
 
 
3b3ebed
 
09141b1
 
 
 
3b3ebed
 
 
 
09141b1
 
3b3ebed
 
09141b1
 
3b3ebed
 
 
 
 
 
 
 
 
09141b1
 
 
3b3ebed
09141b1
 
3b3ebed
09141b1
3b3ebed
09141b1
 
 
3b3ebed
09141b1
 
3b3ebed
09141b1
3b3ebed
 
 
 
 
 
 
09141b1
3b3ebed
 
09141b1
 
 
3b3ebed
 
 
09141b1
 
 
3b3ebed
 
09141b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b3ebed
 
09141b1
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
"""

GraphMind — Knowledge Graph Construction & Reasoning Engine

============================================================

Main Streamlit application.

"""

import streamlit as st
import streamlit.components.v1 as components
import pandas as pd

from src.extractor import EntityExtractor
from src.graph_builder import KnowledgeGraph, ENTITY_COLORS
from src.visualizer import (
    create_pyvis_graph,
    graph_stats_chart,
    centrality_chart,
    community_chart,
)
from src.sample_texts import SAMPLE_TEXTS

# ======================================================================
# Page configuration
# ======================================================================

st.set_page_config(
    page_title="GraphMind | Knowledge Graph",
    page_icon="G",
    layout="wide",
    initial_sidebar_state="expanded",
)

# ======================================================================
# Custom CSS — dark theme with accent colours
# ======================================================================

st.markdown(
    """

    <style>

    /* ---- Global ---- */

    .stApp {

        background-color: #0a0a0a;

        color: #e0e0e0;

    }



    /* ---- Sidebar ---- */

    section[data-testid="stSidebar"] {

        background-color: #111111;

        border-right: 1px solid #1e1e1e;

    }



    /* ---- Headers ---- */

    h1, h2, h3, h4 {

        color: #ffffff !important;

    }



    /* ---- Metric cards ---- */

    div[data-testid="stMetric"] {

        background: linear-gradient(135deg, #111111 0%, #1a1a2e 100%);

        border: 1px solid #1e1e1e;

        border-radius: 12px;

        padding: 16px 20px;

    }

    div[data-testid="stMetric"] label {

        color: #888888 !important;

    }

    div[data-testid="stMetric"] div[data-testid="stMetricValue"] {

        color: #00ff88 !important;

        font-weight: 700;

    }



    /* ---- Buttons ---- */

    .stButton > button {

        background: linear-gradient(135deg, #00ff88 0%, #00d4ff 100%);

        color: #0a0a0a;

        border: none;

        border-radius: 8px;

        font-weight: 700;

        padding: 0.5rem 1.5rem;

        transition: all 0.3s ease;

    }

    .stButton > button:hover {

        transform: translateY(-2px);

        box-shadow: 0 4px 20px rgba(0,255,136,0.3);

    }



    /* ---- Tabs ---- */

    .stTabs [data-baseweb="tab-list"] {

        gap: 8px;

    }

    .stTabs [data-baseweb="tab"] {

        background-color: #1a1a1a;

        border-radius: 8px 8px 0 0;

        color: #888888;

        padding: 8px 20px;

    }

    .stTabs [aria-selected="true"] {

        background-color: #1e1e2e;

        color: #00ff88 !important;

    }



    /* ---- DataFrame ---- */

    .stDataFrame {

        border: 1px solid #1e1e1e;

        border-radius: 8px;

    }



    /* ---- Expanders ---- */

    .streamlit-expanderHeader {

        background-color: #111111;

        border-radius: 8px;

    }



    /* ---- Success / info banners ---- */

    .stAlert {

        background-color: #111111;

        border: 1px solid #1e1e1e;

        border-radius: 8px;

    }



    /* ---- Accent text helpers ---- */

    .accent-green { color: #00ff88; font-weight: 700; }

    .accent-blue  { color: #00d4ff; font-weight: 700; }



    /* ---- Legend colour pills ---- */

    .legend-pill {

        display: inline-block;

        padding: 3px 12px;

        border-radius: 20px;

        margin: 2px 4px;

        font-size: 0.82rem;

        font-weight: 600;

        color: #0a0a0a;

    }



    /* ---- Divider ---- */

    hr {

        border-color: #1e1e1e;

    }

    </style>

    """,
    unsafe_allow_html=True,
)


# ======================================================================
# Sidebar
# ======================================================================

with st.sidebar:
    st.markdown("## GraphMind")
    st.markdown(
        "<span class='accent-green'>Knowledge Graph</span> "
        "<span class='accent-blue'>Construction & Reasoning</span>",
        unsafe_allow_html=True,
    )
    st.markdown("---")

    # --- Input source ---
    st.markdown("### Text Source")
    input_mode = st.radio(
        "Choose input method",
        ["Demo Texts", "Paste Your Own"],
        label_visibility="collapsed",
    )

    text_to_process = ""

    if input_mode == "Demo Texts":
        selected_demo = st.selectbox(
            "Select a demo text",
            list(SAMPLE_TEXTS.keys()),
        )
        text_to_process = SAMPLE_TEXTS[selected_demo]
        with st.expander("Preview text", expanded=False):
            st.caption(text_to_process[:500] + "…")
    else:
        text_to_process = st.text_area(
            "Paste your text below",
            height=250,
            placeholder="Enter text containing named entities…",
        )

    st.markdown("---")

    # --- Extraction settings ---
    st.markdown("### Extraction Settings")
    entity_types = st.multiselect(
        "Entity types to extract",
        ["PERSON", "ORG", "LOCATION", "DATE", "TECHNOLOGY"],
        default=["PERSON", "ORG", "LOCATION", "DATE", "TECHNOLOGY"],
    )

    min_mentions = st.slider(
        "Minimum mentions for nodes",
        min_value=1,
        max_value=5,
        value=1,
        help="Only show entities mentioned at least this many times.",
    )

    st.markdown("---")

    # --- Build button ---
    build_clicked = st.button(" Build Knowledge Graph", use_container_width=True)

    st.markdown("---")
    st.markdown(
        "<div style='text-align:center;color:#555;font-size:0.75rem;'>"
        "Built by <b>Yogesh Kuchimanchi</b><br>MIT License</div>",
        unsafe_allow_html=True,
    )


# ======================================================================
# Main area — Header
# ======================================================================

st.markdown(
    "<h1 style='text-align:center;'>"
    " Graph<span class='accent-green'>Mind</span></h1>",
    unsafe_allow_html=True,
)
st.markdown(
    "<p style='text-align:center;color:#888;margin-top:-10px;'>"
    "Construct knowledge graphs from unstructured text using rule-based NER "
    "and graph reasoning.</p>",
    unsafe_allow_html=True,
)

# Colour legend
legend_html = " ".join(
    f"<span class='legend-pill' style='background:{color};'>{label}</span>"
    for label, color in ENTITY_COLORS.items()
)
st.markdown(
    f"<div style='text-align:center;margin-bottom:20px;'>{legend_html}</div>",
    unsafe_allow_html=True,
)


# ======================================================================
# Processing pipeline
# ======================================================================

@st.cache_data(show_spinner=False)
def run_pipeline(text: str, types: tuple):
    """Run NER + graph construction and cache results."""
    extractor = EntityExtractor()
    entities = extractor.extract(text)

    # Filter entity types
    entities = [e for e in entities if e["label"] in types]

    relationships = extractor.extract_relationships(text, entities)

    kg = KnowledgeGraph()
    kg.add_entities(entities)
    kg.add_relationships(relationships)

    stats = kg.get_stats()
    graph_html = create_pyvis_graph(kg)

    return entities, relationships, kg, stats, graph_html


# ======================================================================
# Run on button click OR first load with demo text
# ======================================================================

if "has_run" not in st.session_state:
    st.session_state.has_run = False

if build_clicked and text_to_process.strip():
    st.session_state.has_run = True
    st.session_state.text = text_to_process
    st.session_state.types = tuple(entity_types)

# Auto-run on first visit with demo text
if not st.session_state.has_run and input_mode == "Demo Texts":
    st.session_state.has_run = True
    st.session_state.text = text_to_process
    st.session_state.types = tuple(entity_types)

if st.session_state.has_run:
    with st.spinner("Extracting entities and building graph…"):
        entities, relationships, kg, stats, graph_html = run_pipeline(
            st.session_state.text, st.session_state.types
        )

    # ==================================================================
    # Metrics row
    # ==================================================================
    m1, m2, m3, m4 = st.columns(4)
    m1.metric("Total Nodes", stats["total_nodes"])
    m2.metric("Total Edges", stats["total_edges"])
    m3.metric("Communities", stats["num_communities"])
    m4.metric("Entity Types", len(stats["entity_type_counts"]))

    st.markdown("---")

    # ==================================================================
    # Tabs
    # ==================================================================
    tab_graph, tab_entities, tab_relations, tab_stats = st.tabs(
        [" Interactive Graph", " Entities", " Relationships", " Statistics"]
    )

    # --- Interactive Graph ---
    with tab_graph:
        st.markdown("#### Interactive Knowledge Graph")
        st.caption("Drag, zoom, and hover nodes for details.")
        components.html(graph_html, height=680, scrolling=False)

    # --- Entities table ---
    with tab_entities:
        st.markdown("#### Extracted Entities")
        if entities:
            df_ent = pd.DataFrame(entities)
            df_ent = df_ent[["text", "label", "start", "end"]]
            df_ent.columns = ["Entity", "Type", "Start", "End"]

            # Colour-coded type column
            st.dataframe(
                df_ent.style.apply(
                    lambda row: [
                        "",
                        f"color: {ENTITY_COLORS.get(row['Type'], '#888')}",
                        "",
                        "",
                    ],
                    axis=1,
                ),
                use_container_width=True,
                height=450,
            )
            st.caption(f"Total: **{len(entities)}** entities extracted.")
        else:
            st.info("No entities found. Try different text or settings.")

    # --- Relationships table ---
    with tab_relations:
        st.markdown("#### Extracted Relationships")
        if relationships:
            df_rel = pd.DataFrame(relationships)
            df_rel = df_rel[["source", "relation", "target", "source_label", "target_label"]]
            df_rel.columns = ["Source", "Relation", "Target", "Src Type", "Tgt Type"]
            st.dataframe(df_rel, use_container_width=True, height=450)
            st.caption(f"Total: **{len(relationships)}** relationships inferred.")
        else:
            st.info("No relationships found.")

    # --- Statistics ---
    with tab_stats:
        st.markdown("#### Graph Analytics")

        col_left, col_right = st.columns(2)

        with col_left:
            fig_dist = graph_stats_chart(stats)
            st.plotly_chart(fig_dist, use_container_width=True)

        with col_right:
            fig_community = community_chart(stats["communities"])
            st.plotly_chart(fig_community, use_container_width=True)

        st.markdown("---")
        fig_central = centrality_chart(stats["top_central_nodes"])
        st.plotly_chart(fig_central, use_container_width=True)

        with st.expander("Community Details"):
            for i, comm in enumerate(stats["communities"]):
                st.markdown(
                    f"**Community {i+1}** ({len(comm)} members): "
                    + ", ".join(comm)
                )

        with st.expander("Raw Statistics"):
            st.json(
                {
                    "density": round(stats["density"], 6),
                    "total_nodes": stats["total_nodes"],
                    "total_edges": stats["total_edges"],
                    "entity_type_counts": stats["entity_type_counts"],
                    "relation_type_counts": stats["relation_type_counts"],
                    "num_communities": stats["num_communities"],
                }
            )

else:
    # Placeholder when nothing has been processed yet
    st.markdown(
        "<div style='text-align:center;padding:80px 20px;color:#555;'>"
        "<h3>Paste text or select a demo, then click "
        "<span class='accent-green'>Build Knowledge Graph</span></h3>"
        "<p>The engine will extract entities, infer relationships, "
        "and visualise an interactive knowledge graph.</p>"
        "</div>",
        unsafe_allow_html=True,
    )