-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2571 lines (2186 loc) · 111 KB
/
streamlit_app.py
File metadata and controls
2571 lines (2186 loc) · 111 KB
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Streamlit App - Competitive Intelligence Dashboard
A beautiful, agentic-powered dashboard for Honeywell competitive intelligence.
Features:
1. 📊 Interactive Knowledge Graph Visualization
2. 📋 Product Specification Comparison Table
3. 🔍 Head-to-Head Product Comparison
4. ✅ Human-in-the-Loop Verification
5. 🤖 Run Agentic Pipeline from UI
"""
import streamlit as st
import streamlit.components.v1 as components
import json
import pandas as pd
from typing import List, Dict, Any, Optional
from neo4j import GraphDatabase
from pyvis.network import Network
import tempfile
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
from src.config.settings import get_neo4j_config
from src.pipeline.chroma_store import find_best_evidence_for_relationship, get_chunk_by_id
from src.ontology.specifications import PRESSURE_TRANSMITTER_ONTOLOGY
# =============================================================================
# PAGE CONFIG & STYLES
# =============================================================================
st.set_page_config(
page_title="Competitive Intelligence Database",
page_icon="🎯",
layout="wide",
initial_sidebar_state="expanded",
)
# Custom CSS for professional styling (neutral light greys)
st.markdown("""
<style>
.main { background: linear-gradient(180deg, #f7f7f8 0%, #f1f3f5 100%); }
.main-header {
background: linear-gradient(135deg, #f5f5f6 0%, #e5e7eb 100%);
padding: 2rem 2.5rem;
border-radius: 16px;
margin-bottom: 2rem;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.10);
border: 1px solid #e5e7eb;
}
.main-header h1 { font-family: 'Inter', sans-serif; letter-spacing: 0.5px; color: #111827; margin: 0; }
.main-header p { color: #374151; margin: 0.2rem 0 0; font-size: 1rem; }
.section-header {
background: linear-gradient(90deg, #f5f6f7 0%, #e8ebef 100%);
padding: 1rem 1.5rem;
border-radius: 12px;
margin: 2rem 0 1rem 0;
border-left: 4px solid #9ca3af;
}
.section-header h2 { color: #111827; margin: 0; font-size: 1.3rem; font-weight: 600; }
.metric-card {
background: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 1rem 1.25rem;
box-shadow: 0 8px 20px rgba(0,0,0,0.08);
color: #111827;
}
.metric-value { font-size: 1.8rem; font-weight: 700; color: #111827; }
.metric-label { font-size: 0.9rem; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
.dataframe { background: #ffffff !important; border-radius: 8px; overflow: hidden; }
.dataframe th { background: #f3f4f6 !important; color: #111827 !important; font-weight: 600 !important; text-transform: uppercase; letter-spacing: 0.5px; padding: 12px 16px !important; }
.dataframe td { background: #ffffff !important; color: #1f2937 !important; padding: 10px 16px !important; border-bottom: 1px solid #e5e7eb !important; }
.dataframe tr:hover td { background: #f3f4f6 !important; }
.comparison-winner { background: #e5e7eb !important; color: #111827 !important; font-weight: 600; }
.comparison-loser { background: #f9fafb !important; color: #6b7280 !important; }
.streamlit-expanderHeader { background: #f3f4f6; border-radius: 8px; }
.css-1d391kg { background: linear-gradient(180deg, #f7f7f8 0%, #f1f3f5 100%); }
.css-1d391kg p, .css-1d391kg label { color: #111827 !important; }
.stButton > button {
background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
color: #111827;
border: none;
border-radius: 8px;
padding: 0.75rem 1.5rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
transition: all 0.2s;
}
.stButton > button:hover {
background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%);
box-shadow: 0 4px 15px rgba(156, 163, 175, 0.35);
transform: translateY(-1px);
}
.stDataFrame { background: #ffffff; border-radius: 10px; border: 1px solid #e5e7eb; }
.stTabs [data-baseweb="tab-list"] { gap: 8px; }
.stTabs [data-baseweb="tab"] {
background: #f3f4f6;
border-radius: 8px 8px 0 0;
padding: 0.75rem 1.5rem;
color: #4b5563;
}
.stTabs [data-baseweb="tab"]:hover { color: #111827; }
.stTabs [data-baseweb="tab"][aria-selected="true"] {
background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
color: #111827;
}
</style>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
""", unsafe_allow_html=True)
# =============================================================================
# DATABASE FUNCTIONS
# =============================================================================
def get_neo4j_driver():
"""Create Neo4j connection."""
cfg = get_neo4j_config()
return GraphDatabase.driver(cfg['uri'], auth=(cfg['user'], cfg['password']))
def fetch_all_products_with_specs() -> pd.DataFrame:
"""Fetch all products with their specifications for the comparison table."""
driver = get_neo4j_driver()
with driver.session() as session:
result = session.run("""
MATCH (c:Company)-[:OFFERS_PRODUCT]->(p:Product)
OPTIONAL MATCH (p)-[:HAS_SPEC]->(s:Specification)
OPTIONAL MATCH (p)-[:HAS_PRICE]->(price:Price)
OPTIONAL MATCH (p)-[:HAS_REVIEW]->(r:Review)
RETURN
c.name as company,
p.name as product,
collect(DISTINCT {spec_type: s.spec_type, value: s.value}) as specifications,
price.name as price,
p.source_urls as sources,
collect(DISTINCT {text: r.text, rating: r.rating, source: r.source}) as reviews
ORDER BY c.name, p.name
""")
rows = []
for record in result:
row = {
'Company': record['company'],
'Product': record['product'],
'Price': record['price'] or '-',
'Sources': record['sources'] or [],
'Review Count': len([rv for rv in record['reviews'] or [] if rv.get('text')]),
}
# First review snippet
first_review = None
if record['reviews']:
for rv in record['reviews']:
if rv.get('text'):
first_review = rv
break
if first_review:
snippet = (first_review.get('text', '') or '')[:120]
rating = first_review.get('rating', '')
source = first_review.get('source', '')
row['Review Snippet'] = f"{rating} - {snippet} ({source})" if rating else f"{snippet} ({source})"
else:
row['Review Snippet'] = ''
# Flatten specifications
for spec in record['specifications']:
if spec['spec_type'] and spec['value']:
spec_display = spec['spec_type'].replace('_', ' ').title()
row[spec_display] = spec['value']
rows.append(row)
driver.close()
if rows:
df = pd.DataFrame(rows)
return df
return pd.DataFrame()
def fetch_graph_data():
"""Fetch all nodes and relationships for visualization."""
driver = get_neo4j_driver()
with driver.session() as session:
result = session.run("""
MATCH (source)-[rel]->(target)
RETURN
elementId(source) as source_id,
labels(source)[0] as source_label,
source.name as source_name,
type(rel) as relationship_type,
elementId(target) as target_id,
labels(target)[0] as target_label,
target.name as target_name,
rel.source_urls as rel_sources,
rel.evidence_ids as rel_evidence,
rel.snippet as rel_snippet
""")
nodes = {}
edges = []
for record in result:
source_id = record['source_id']
if source_id not in nodes:
source_name = record['source_name'] or ""
source_group = record['source_label']
# For nodes with product|name format, show item name with short product prefix
# This makes each node VISUALLY distinct even if they have the same segment/need name
labels_with_pipe = ["Specification", "Price", "Review", "CustomerSegment", "CustomerNeed"]
if source_group in labels_with_pipe and "|" in source_name:
parts = source_name.split("|", 1)
product_short = parts[0].strip()[:8] # Short product name (e.g., "3051S")
item_name = parts[1].strip()[:18] # Item name
# Show as "Segment (Product)" to make visually distinct
clean_source_label = f"{item_name}\n({product_short})"
hover_title = f"Product: {parts[0]}\n{source_group}: {parts[1]}"
else:
clean_source_label = source_name[:30]
hover_title = source_name
nodes[source_id] = {
'id': source_id,
'label': clean_source_label,
'title': hover_title,
'group': source_group,
'full_name': source_name
}
target_id = record['target_id']
if target_id not in nodes:
target_name = record['target_name'] or ""
target_group = record['target_label']
labels_with_pipe = ["Specification", "Price", "Review", "CustomerSegment", "CustomerNeed"]
if target_group in labels_with_pipe and "|" in target_name:
parts = target_name.split("|", 1)
product_short = parts[0].strip()[:8]
item_name = parts[1].strip()[:18]
clean_target_label = f"{item_name}\n({product_short})"
hover_title = f"Product: {parts[0]}\n{target_group}: {parts[1]}"
else:
clean_target_label = target_name[:30]
hover_title = target_name
nodes[target_id] = {
'id': target_id,
'label': clean_target_label,
'title': hover_title,
'group': target_group,
'full_name': target_name
}
edges.append({
'from': source_id,
'to': target_id,
'label': record['relationship_type'],
'title': record['relationship_type'],
'sources': record.get('rel_sources') or [],
'evidence_ids': record.get('rel_evidence') or [],
'snippet': record.get('rel_snippet', "") or "",
})
driver.close()
return list(nodes.values()), edges
def fetch_graph_stats() -> Dict[str, int]:
"""Get statistics about the knowledge graph."""
driver = get_neo4j_driver()
with driver.session() as session:
stats = {}
result = session.run("""
MATCH (n)
RETURN labels(n)[0] as label, count(n) as count
""")
stats['nodes'] = {record['label']: record['count'] for record in result}
result = session.run("""
MATCH ()-[r]->()
RETURN type(r) as type, count(r) as count
""")
stats['relationships'] = {record['type']: record['count'] for record in result}
driver.close()
return stats
def _is_valid_http_url(url: str) -> bool:
if not url or not isinstance(url, str):
return False
url = url.strip()
return url.startswith("http://") or url.startswith("https://")
def fetch_all_relationships():
"""Fetch all relationships for verification."""
driver = get_neo4j_driver()
with driver.session() as session:
result = session.run("""
MATCH (source)-[rel]->(target)
RETURN
elementId(rel) as rel_id,
labels(source)[0] as source_label,
source.name as source_name,
type(rel) as relationship_type,
labels(target)[0] as target_label,
target.name as target_name,
rel.source_urls as source_urls,
rel.evidence_ids as evidence_ids,
rel.snippet as snippet
ORDER BY relationship_type, source_name
""")
relationships = []
for record in result:
relationships.append({
'rel_id': record['rel_id'],
'source_label': record['source_label'],
'source_name': record['source_name'],
'relationship_type': record['relationship_type'],
'target_label': record['target_label'],
'target_name': record['target_name'],
'source_urls': record['source_urls'] or [],
'evidence_ids': record['evidence_ids'] or [],
'snippet': record['snippet'] or ""
})
driver.close()
return relationships
def delete_relationships(rel_ids: List[int]):
"""Delete relationships from Neo4j."""
driver = get_neo4j_driver()
with driver.session() as session:
for rel_id in rel_ids:
session.run("""
MATCH ()-[r]->()
WHERE id(r) = $rel_id
DELETE r
""", rel_id=rel_id)
driver.close()
# =============================================================================
# VISUALIZATION FUNCTIONS
# =============================================================================
def create_network_graph(nodes, edges):
"""Create beautiful interactive network graph with white background."""
net = Network(
height="820px",
width="100%",
bgcolor="#ffffff",
font_color="#1f2937",
directed=True
)
net.set_options("""
{
"layout": {
"hierarchical": {
"enabled": false
}
},
"physics": {
"enabled": true,
"barnesHut": {
"gravitationalConstant": -25000,
"centralGravity": 0.3,
"springLength": 200,
"springConstant": 0.04,
"damping": 0.6
},
"stabilization": {
"enabled": true,
"iterations": 200
}
},
"nodes": {
"font": {"size": 14, "face": "Inter, sans-serif", "color": "#1f2937"},
"borderWidth": 3,
"borderWidthSelected": 4,
"shadow": {
"enabled": true,
"color": "rgba(0,0,0,0.15)",
"size": 10
}
},
"edges": {
"font": {"size": 11, "align": "middle", "color": "#6b7280"},
"arrows": {"to": {"enabled": true, "scaleFactor": 0.6}},
"smooth": {"type": "continuous"},
"width": 2,
"color": {"color": "#9ca3af", "highlight": "#3b82f6"}
},
"interaction": {
"hover": true,
"tooltipDelay": 100,
"navigationButtons": true,
"keyboard": true
}
}
""")
# Neutral color scheme
colors = {
'Company': {'background': '#1f2937', 'border': '#111827'},
'Product': {'background': '#4b5563', 'border': '#374151'},
'Price': {'background': '#6b7280', 'border': '#4b5563'},
'Specification': {'background': '#9ca3af', 'border': '#6b7280'},
'Review': {'background': '#d1d5db', 'border': '#9ca3af'}
}
# Special color for Honeywell (center node)
honeywell_color = {'background': '#111827', 'border': '#030712'}
for node in nodes:
group = node['group']
# Only treat the Honeywell COMPANY as the fixed center node to avoid overlap
label_text = node.get('label', '') or ''
is_honeywell = (group == 'Company') and ('Honeywell' in label_text)
# Uniform node sizing for readability
size = 50 if is_honeywell else 35
color = honeywell_color if is_honeywell else colors.get(group, {'background': '#6b7280', 'border': '#9ca3af'})
font_cfg = {'size': 18, 'color': '#1f2937', 'bold': True} if is_honeywell else {'size': 13, 'color': '#1f2937'}
net.add_node(
node['id'],
label=node['label'],
title=node['title'],
color=color,
group=group,
size=size,
font=font_cfg,
x=0 if is_honeywell else None,
y=0 if is_honeywell else None,
fixed={'x': True, 'y': True} if is_honeywell else None,
physics=not is_honeywell
)
for edge in edges:
net.add_edge(
edge['from'],
edge['to'],
label=edge['label'].replace('_', ' '),
title=edge['title']
)
return net
def create_comparison_table(products_df: pd.DataFrame, selected_products: List[str]) -> pd.DataFrame:
"""Create a head-to-head comparison table for selected products."""
if not selected_products or len(selected_products) < 2:
return pd.DataFrame()
# Filter to selected products
comparison_df = products_df[products_df['Product'].isin(selected_products)].copy()
if comparison_df.empty:
return pd.DataFrame()
# Transpose for comparison view
comparison_df = comparison_df.set_index('Product').T
return comparison_df
# =============================================================================
# EVALUATION HELPER FUNCTIONS
# =============================================================================
import re
def calculate_match_score(extracted_value: str, source_text: str) -> dict:
"""
Calculate how well an extracted value matches the source text.
Returns match percentage and details.
"""
if not extracted_value or not source_text:
return {"score": 0, "exact_match": False, "tokens_found": 0, "total_tokens": 0, "matched_tokens": [], "numbers_matched": [], "numbers_in_extraction": []}
extracted_lower = extracted_value.lower().strip()
source_lower = source_text.lower()
# Check exact match
exact_match = extracted_lower in source_lower
# Token-based matching (for multi-word extractions)
# Remove common stop words and punctuation
stop_words = {'the', 'a', 'an', 'is', 'are', 'was', 'were', 'for', 'of', 'to', 'in', 'on', 'with', 'and', 'or'}
# Clean tokens - only keep meaningful words (3+ chars)
tokens = re.findall(r'[a-z]{3,}', extracted_lower)
tokens = [t for t in tokens if t and t not in stop_words]
matched_tokens = []
for token in tokens:
if token in source_lower:
matched_tokens.append(token)
tokens_found = len(matched_tokens)
total_tokens = len(tokens) if tokens else 1
token_score = (tokens_found / total_tokens) * 100 if total_tokens > 0 else 0
# Number extraction check - handle decimals properly
# Match numbers including decimals like "0.075", "15000", "±0.04%"
numbers_in_extraction = re.findall(r'\d+\.?\d*', extracted_value)
# Filter out single digit numbers that are too common (0, 1, etc.)
numbers_in_extraction = [n for n in numbers_in_extraction if len(n) >= 2 or '.' in n]
# Also try to match the full pattern (e.g., "7200 psi" or "0.04%")
# This is more meaningful than just matching "7200"
full_patterns_matched = []
numbers_matched = []
for num in numbers_in_extraction:
# Check if the number appears in source with similar context
# Look for the number in source
if num in source_text:
numbers_matched.append(num)
# Try to find context around it
idx = source_text.find(num)
if idx != -1:
context = source_text[max(0, idx-10):idx+len(num)+15]
full_patterns_matched.append(context.strip())
numbers_score = (len(numbers_matched) / len(numbers_in_extraction) * 100) if numbers_in_extraction else 100
# Combined score (weighted average)
if exact_match:
final_score = 100
elif numbers_in_extraction:
# For specs, numbers matter more - but also credit token matches
final_score = (token_score * 0.3 + numbers_score * 0.7)
else:
final_score = token_score
return {
"score": round(final_score, 1),
"exact_match": exact_match,
"tokens_found": tokens_found,
"total_tokens": total_tokens,
"matched_tokens": matched_tokens,
"numbers_matched": numbers_matched,
"numbers_in_extraction": numbers_in_extraction,
"full_patterns_matched": full_patterns_matched
}
def highlight_matches(source_text: str, matched_tokens: list, max_length: int = 500) -> str:
"""
Return source text with matched tokens highlighted using HTML.
"""
if not source_text:
return "<em>No source text available</em>"
# Truncate if too long
display_text = source_text[:max_length] + "..." if len(source_text) > max_length else source_text
# Escape HTML entities first
display_text = display_text.replace("&", "&").replace("<", "<").replace(">", ">")
# Highlight matched tokens (words get green, numbers get yellow)
for token in matched_tokens:
if token:
# Determine if it's a number or word
is_number = re.match(r'^[\d.]+$', token)
color = "#fef08a" if is_number else "#bbf7d0" # yellow for numbers, green for words
# Case-insensitive replacement with highlighting
pattern = re.compile(re.escape(token), re.IGNORECASE)
display_text = pattern.sub(f'<mark style="background-color: {color}; padding: 0 2px; border-radius: 2px;">{token}</mark>', display_text)
return display_text
def get_score_color(score: float) -> str:
"""Return color based on score."""
if score >= 80:
return "🟢"
elif score >= 50:
return "🟡"
else:
return "🔴"
def evaluate_entity(entity_name: str, entity_value: str, evidence_ids: list) -> dict:
"""
Evaluate a single entity against its source evidence.
Finds the BEST matching chunk to display.
"""
if not evidence_ids:
return {
"entity": entity_name,
"value": entity_value,
"score": 0,
"source_text": "",
"match_details": {"score": 0, "exact_match": False, "matched_tokens": [], "numbers_matched": [], "numbers_in_extraction": [], "full_patterns_matched": []},
"has_evidence": False,
"evidence_ids": [],
"best_chunk_id": None,
"source_url": ""
}
# Get source chunks from ChromaDB and find the BEST matching one
all_chunks = [] # [(chunk_id, chunk_text, source_url)]
for eid in evidence_ids[:10]: # Check up to 10 chunks
try:
chunk = get_chunk_by_id(eid)
if chunk and isinstance(chunk, dict):
doc_text = chunk.get("document", "")
metadata = chunk.get("metadata", {})
source_url = metadata.get("source_url", "") if metadata else ""
if doc_text:
all_chunks.append((eid, doc_text, source_url))
elif chunk and isinstance(chunk, str):
all_chunks.append((eid, chunk, ""))
except:
pass
if not all_chunks:
return {
"entity": entity_name,
"value": entity_value,
"score": 0,
"source_text": "",
"match_details": {"score": 0, "exact_match": False, "matched_tokens": [], "numbers_matched": [], "numbers_in_extraction": [], "full_patterns_matched": []},
"has_evidence": False,
"evidence_ids": evidence_ids,
"best_chunk_id": None,
"source_url": ""
}
# Find the chunk with the best match score
best_score = 0
best_chunk_id = None
best_chunk_text = ""
best_source_url = ""
best_match_details = None
for chunk_id, chunk_text, source_url in all_chunks:
match_result = calculate_match_score(entity_value, chunk_text)
if match_result["score"] > best_score:
best_score = match_result["score"]
best_chunk_id = chunk_id
best_chunk_text = chunk_text
best_source_url = source_url
best_match_details = match_result
# If no chunk had any match, still use the first chunk for display
if best_match_details is None:
best_chunk_id, best_chunk_text, best_source_url = all_chunks[0]
best_match_details = calculate_match_score(entity_value, best_chunk_text)
return {
"entity": entity_name,
"value": entity_value,
"score": best_match_details["score"],
"source_text": best_chunk_text,
"match_details": best_match_details,
"has_evidence": True,
"evidence_ids": evidence_ids,
"best_chunk_id": best_chunk_id,
"source_url": best_source_url,
"total_chunks": len(all_chunks)
}
# =============================================================================
# MAIN APP
# =============================================================================
def main():
# Initialize session state
if 'selected_items' not in st.session_state:
st.session_state.selected_items = set()
if 'verified_relationships' not in st.session_state:
st.session_state.verified_relationships = set()
if 'rejected_relationships' not in st.session_state:
st.session_state.rejected_relationships = set()
if 'selected_products' not in st.session_state:
st.session_state.selected_products = []
# === HEADER ===
st.markdown("""
<div class="main-header">
<h1>🎯 Competitive Intelligence Database</h1>
<p>Competitive Intelligence for Pressure Transmitter Markets | Powered by Agentic AI</p>
</div>
""", unsafe_allow_html=True)
# === SIDEBAR ===
with st.sidebar:
st.markdown("### 🤖 Agentic Pipeline")
st.markdown("Run the AI agent to collect competitive intelligence.")
target_product = st.text_input("Target Product", "SmartLine ST700")
max_competitors = st.slider("Max Competitors", 1, 10, 5)
max_iterations = st.slider("Max Iterations", 10, 50, 30)
if st.button("🚀 Run Agentic Pipeline", width="stretch"):
with st.spinner("🤖 Agent is researching..."):
try:
from src.pipeline.graph_builder import run_pipeline
result = run_pipeline(
max_competitors=max_competitors,
)
st.success("✅ Pipeline complete!")
st.rerun()
except Exception as e:
st.error(f"❌ Error: {str(e)}")
st.markdown("---")
st.markdown("### 📊 Quick Stats")
try:
stats = fetch_graph_stats()
for label, count in stats.get('nodes', {}).items():
st.metric(label, count)
except:
st.info("Connect to Neo4j to see stats")
# === MAIN CONTENT TABS ===
tabs = st.tabs([
"📊 Knowledge Graph",
"🔄 Pipeline Architecture",
"📚 Ontology",
"📋 Specification Table",
"🔍 Compare Products",
"✅ Verify Data",
"🎯 Customer Needs",
"👥 Customer Segments",
"🏠 House of Quality",
"📈 Evaluation"
])
# === TAB 1: KNOWLEDGE GRAPH ===
with tabs[0]:
st.markdown("""
<div class="section-header">
<h2>📊 Knowledge Graph Visualization</h2>
</div>
""", unsafe_allow_html=True)
try:
nodes, edges = fetch_graph_data()
if nodes and edges:
# Metrics row
col1, col2, col3, col4 = st.columns(4)
with col1:
companies = len([n for n in nodes if n['group'] == 'Company'])
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{companies}</div>
<div class="metric-label">Companies</div>
</div>
""", unsafe_allow_html=True)
with col2:
products = len([n for n in nodes if n['group'] == 'Product'])
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{products}</div>
<div class="metric-label">Products</div>
</div>
""", unsafe_allow_html=True)
with col3:
specs = len([n for n in nodes if n['group'] == 'Specification'])
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{specs}</div>
<div class="metric-label">Specifications</div>
</div>
""", unsafe_allow_html=True)
with col4:
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{len(edges)}</div>
<div class="metric-label">Relationships</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Legend
with st.expander("🎨 Graph Legend & Controls"):
col1, col2 = st.columns(2)
with col1:
st.markdown("""
**Node Types:**
- 🔵 **Company** - Competitors
- 🟡 **Product** - Product models
- 🟢 **Price** - Pricing data
- 🔴 **Specification** - Technical specs
- 🟣 **Review** - Customer reviews
""")
with col2:
st.markdown("""
**Controls:**
- **Drag** nodes to rearrange
- **Scroll** to zoom
- **Click** to highlight connections
- **Double-click** to focus
""")
# Render graph
net = create_network_graph(nodes, edges)
with tempfile.NamedTemporaryFile(delete=False, suffix='.html', mode='w', encoding='utf-8') as f:
net.save_graph(f.name)
with open(f.name, 'r', encoding='utf-8') as f2:
html_content = f2.read()
components.html(html_content, height=850, scrolling=False)
else:
st.info("📊 No graph data yet. Run the pipeline to generate data.")
except Exception as e:
st.warning(f"⚠️ Could not load graph: {str(e)}")
# === TAB 2: PIPELINE ARCHITECTURE ===
with tabs[1]:
st.markdown("""
<div class="section-header">
<h2>🔄 LangGraph Agentic Pipeline</h2>
</div>
""", unsafe_allow_html=True)
st.markdown("This shows the architecture of the agentic AI pipeline that collects competitive intelligence.")
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("### Pipeline Visualization")
# Try to load and display the pipeline image
try:
# Generate pipeline diagram from the LangGraph agent
try:
from src.agents.agentic_agent import build_graph
graph = build_graph()
png_bytes = graph.get_graph().draw_mermaid_png()
st.image(png_bytes, caption="LangGraph Agentic Pipeline", width="stretch")
except Exception as e:
# Fallback to text diagram
st.code("""
__start__
│
▼
┌─────────┐
│ agent │ ←── LLM decides tool calls
└────┬────┘
│
▼ (conditional)
┌─────────┐
│ tools │ ←── Executes: search_web, extract_page_content, etc.
└────┬────┘
│
└──────→ back to agent (loop)
""", language="text")
st.caption(f"Live diagram unavailable: {e}")
except Exception as e:
st.warning(f"Could not load pipeline visualization: {e}")
with col2:
st.markdown("### How It Works")
st.markdown("""
**The LangGraph Agent Loop:**
```
__start__
│
▼
┌─────────┐
│ agent │◄────────┐
│ (LLM) │ │
└────┬────┘ │
│ │
▼ │
┌─────────┐ │
│ tools │─────────┘
└────┬────┘
│ (when complete)
▼
┌─────────┐
│ __end__ │ → Neo4j
└─────────┘
```
""")
st.markdown("---")
st.markdown("### Available Tools")
tools_info = {
"🔍 search_web": "Search for competitors, products, specs",
"📄 extract_page": "Get full content from a URL",
"🏢 save_competitor": "Store a competitor company",
"📦 save_product": "Store a product model",
"📊 save_specification": "Store a technical spec",
"💰 save_price": "Store a price",
"📝 save_review": "Store a customer review",
"✅ mark_complete": "Signal mission complete",
}
for tool, desc in tools_info.items():
st.markdown(f"- **{tool}**: {desc}")
st.markdown("---")
# Show agent decision flow
st.markdown("### Agent Decision Flow")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown("""
<div style="background: #fee2e2; padding: 1rem; border-radius: 8px; text-align: center;">
<strong>1️⃣ OBSERVE</strong><br>
<small>Check current state</small>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="background: #fef3c7; padding: 1rem; border-radius: 8px; text-align: center;">
<strong>2️⃣ THINK</strong><br>
<small>What's missing?</small>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div style="background: #d1fae5; padding: 1rem; border-radius: 8px; text-align: center;">
<strong>3️⃣ ACT</strong><br>
<small>Call a tool</small>
</div>
""", unsafe_allow_html=True)
with col4:
st.markdown("""
<div style="background: #dbeafe; padding: 1rem; border-radius: 8px; text-align: center;">
<strong>4️⃣ UPDATE</strong><br>
<small>Save to state</small>
</div>
""", unsafe_allow_html=True)
# === TAB 3: ONTOLOGY ===
with tabs[2]:
st.markdown("""
<div class="section-header">
<h2>📚 Specification Ontology</h2>
</div>
""", unsafe_allow_html=True)
st.markdown("""
The **ontology** defines what specifications matter for pressure transmitters and how to normalize them
for head-to-head comparison. It's a hybrid human + AI approach:
- **Human-defined**: The specification categories, units, and importance levels
- **AI-extracted**: Values are extracted from datasheets and mapped to the ontology
- **AI-derived**: New specs found by AI that aren't in the ontology are tagged separately
""")
st.markdown("---")
# Display ontology categories
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("### 🎯 High-Priority Specifications")
st.markdown("*These are critical for competitive comparison (★★★★★)*")
high_priority = [
("**Pressure Range**", "Operating pressure span", "psi (normalized from bar, kPa, MPa)"),
("**Accuracy**", "Measurement precision", "% of full scale"),
("**Output Signal**", "Communication protocol", "4-20mA, HART, Profibus, etc."),
("**Measurement Type**", "Gauge, Absolute, Differential", "Enum values"),
]
for name, desc, unit in high_priority:
st.markdown(f"- {name}: {desc} → *{unit}*")
st.markdown("### 🔧 Physical Specifications")
st.markdown("*Connection and material specs (★★★★)*")