-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1818 lines (1503 loc) · 74.2 KB
/
app.py
File metadata and controls
1818 lines (1503 loc) · 74.2 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
import streamlit as st
import google.generativeai as genai
import requests
from bs4 import BeautifulSoup
import time
import random
import re
import json
import hashlib
import urllib.parse
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
from dataclasses import dataclass
import asyncio
import aiohttp
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- 🔐 Configuration & Models ---
@dataclass
class SearchResult:
id: int
title: str
snippet: str
url: str
domain: str
date: Optional[str] = None
credibility_score: float = 0.0
content: str = ""
word_count: int = 0
sentiment: str = "neutral"
@dataclass
class ResearchConfig:
search_mode: str
source_count: int
citation_style: str
include_perspectives: bool
future_insights: bool
data_visualization: bool
executive_summary: bool
historical_context: bool
expert_quotes: bool
fact_check: bool
semantic_analysis: bool
competitive_analysis: bool
class ResearchEngine:
def __init__(self):
self.setup_apis()
self.content_cache = {}
self.credibility_domains = {
'edu': 0.9, 'gov': 0.95, 'org': 0.7, 'com': 0.5,
'nature.com': 0.98, 'science.org': 0.98, 'arxiv.org': 0.85,
'pubmed.ncbi.nlm.nih.gov': 0.95, 'scholar.google.com': 0.8
}
def setup_apis(self):
"""Initialize API configurations"""
try:
self.gemini_key = st.secrets["GEMINI_API_KEY"]
self.serp_key = st.secrets["SERPAPI_KEY"]
genai.configure(api_key=self.gemini_key)
self.model = genai.GenerativeModel("gemini-2.0-flash")
except Exception as e:
st.error(f"API Configuration Error: {e}")
logger.error(f"API setup failed: {e}")
def calculate_credibility_score(self, url: str, content: str = "") -> float:
"""Calculate source credibility based on domain and content quality"""
try:
domain = urllib.parse.urlparse(url).netloc.lower()
base_score = 0.5
# Domain-based scoring
for trusted_domain, score in self.credibility_domains.items():
if trusted_domain in domain:
base_score = score
break
# Content quality indicators
if content:
quality_indicators = [
(r'\bcitation\b|\breference\b|\bstudy\b', 0.1),
(r'\bdoi:\b|\barxiv:\b', 0.15),
(r'\bpeer.?reviewed\b|\bjournal\b', 0.1),
(r'\bdata\b|\bstatistics\b|\bresearch\b', 0.05)
]
for pattern, boost in quality_indicators:
if re.search(pattern, content, re.IGNORECASE):
base_score = min(1.0, base_score + boost)
return round(base_score, 2)
except:
return 0.5
def enhanced_search(self, query: str, num_results: int = 20) -> List[SearchResult]:
"""Enhanced search with multiple parameters and result processing"""
# --- Start of Corrected Block ---
try:
# Primary search
results = []
search_params = {
"q": query,
"engine": "google",
"api_key": self.serp_key,
"num": num_results,
"hl": "en",
"gl": "us",
"safe": "active"
}
# Use a try-except block to catch timeout errors gracefully
try:
response = requests.get("https://serpapi.com/search", params=search_params, timeout=30)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
data = response.json()
organic_results = data.get("organic_results", [])
except requests.exceptions.RequestException as e:
logger.warning(f"Primary search request failed: {e}")
organic_results = [] # Treat as no results on error
# Also search for academic sources
academic_query = f"{query} site:edu OR site:arxiv.org OR site:pubmed.ncbi.nlm.nih.gov"
academic_params = search_params.copy()
academic_params["q"] = academic_query
academic_params["num"] = min(10, num_results // 2)
# Use another try-except block for the academic search
try:
academic_response = requests.get("https://serpapi.com/search", params=academic_params, timeout=20)
academic_response.raise_for_status()
academic_data = academic_response.json()
organic_results.extend(academic_data.get("organic_results", [])[:5])
except requests.exceptions.RequestException as e:
logger.warning(f"Academic search failed, continuing with standard results: {e}")
for idx, result in enumerate(organic_results[:num_results]):
try:
url = result.get("link", "")
domain = urllib.parse.urlparse(url).netloc
search_result = SearchResult(
id=idx + 1,
title=result.get("title", "Untitled"),
snippet=result.get("snippet", ""),
url=url,
domain=domain,
date=result.get("date", None),
credibility_score=self.calculate_credibility_score(url, result.get("snippet", ""))
)
results.append(search_result)
except Exception as e:
logger.warning(f"Error processing search result {idx}: {e}")
continue
# Sort by credibility score (descending)
results.sort(key=lambda x: x.credibility_score, reverse=True)
return results
except Exception as e:
st.error(f"Search failed: {e}")
logger.error(f"Enhanced search failed: {e}")
return []
# --- End of Corrected Block ---
def extract_content_parallel(self, results: List[SearchResult], max_workers: int = 5) -> List[SearchResult]:
"""Extract content from multiple URLs in parallel"""
def fetch_single_content(result: SearchResult) -> SearchResult:
try:
content = self.fetch_content_advanced(result.url)
result.content = content
result.word_count = len(content.split())
result.credibility_score = self.calculate_credibility_score(result.url, content)
return result
except Exception as e:
logger.warning(f"Failed to fetch content for {result.url}: {e}")
return result
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_result = {executor.submit(fetch_single_content, result): result for result in results}
for future in as_completed(future_to_result):
try:
future.result()
except Exception as e:
logger.error(f"Thread execution failed: {e}")
return results
def fetch_content_advanced(self, url: str) -> str:
"""Advanced content extraction with better parsing and caching"""
if url in self.content_cache:
return self.content_cache[url]
try:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
}
response = requests.get(url, headers=headers, timeout=150, verify=False)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Remove unwanted elements
for element in soup(['script', 'style', 'header', 'footer', 'nav', 'aside',
'advertisement', '.ad', '#ad', '.sidebar', '.menu']):
if element:
element.decompose()
# Try to find main content areas
main_content = None
content_selectors = [
'main', 'article', '.main-content', '.content', '.post-content',
'.article-body', '.entry-content', '#main-content', '.article-text'
]
for selector in content_selectors:
main_content = soup.select_one(selector)
if main_content:
break
if not main_content:
main_content = soup.find('body') or soup
# Extract and clean text
text = main_content.get_text(separator=' ', strip=True)
text = re.sub(r'\s+', ' ', text)
text = re.sub(r'[\r\n\t]+', ' ', text)
# Limit content length
if len(text) > 3000:
sentences = text.split('. ')
truncated = []
char_count = 0
for sentence in sentences:
if char_count + len(sentence) > 3000:
break
truncated.append(sentence)
char_count += len(sentence) + 2
text = '. '.join(truncated) + '...'
# Cache the result
self.content_cache[url] = text
return text
except Exception as e:
logger.warning(f"Content extraction failed for {url}: {e}")
return f"Content extraction failed: {str(e)[:100]}"
def analyze_sentiment_and_bias(self, content: str) -> Dict[str, any]:
"""Analyze content sentiment and potential bias"""
try:
# Simple sentiment analysis based on keywords
positive_words = ['excellent', 'great', 'amazing', 'outstanding', 'beneficial',
'effective', 'successful', 'positive', 'good', 'better']
negative_words = ['terrible', 'awful', 'bad', 'harmful', 'dangerous', 'failed',
'unsuccessful', 'negative', 'worse', 'problematic']
content_lower = content.lower()
pos_count = sum(1 for word in positive_words if word in content_lower)
neg_count = sum(1 for word in negative_words if word in content_lower)
if pos_count > neg_count * 1.5:
sentiment = "positive"
elif neg_count > pos_count * 1.5:
sentiment = "negative"
else:
sentiment = "neutral"
# Bias indicators
bias_indicators = {
'emotional_language': len(re.findall(r'\b(amazing|terrible|shocking|unbelievable)\b', content_lower)),
'absolute_statements': len(re.findall(r'\b(always|never|all|none|everyone|nobody)\b', content_lower)),
'personal_opinions': len(re.findall(r'\b(i think|in my opinion|i believe|personally)\b', content_lower))
}
bias_score = sum(bias_indicators.values()) / max(len(content.split()), 1) * 100
return {
'sentiment': sentiment,
'bias_score': round(bias_score, 2),
'bias_indicators': bias_indicators
}
except:
return {'sentiment': 'neutral', 'bias_score': 0, 'bias_indicators': {}}
def generate_visualizations(self, query: str, results: List[SearchResult]) -> List[Dict]:
"""Generate data visualizations based on search results"""
try:
visualizations = []
# Source credibility distribution
credibility_scores = [r.credibility_score for r in results if r.credibility_score > 0]
if credibility_scores:
fig_credibility = px.histogram(
x=credibility_scores,
nbins=10,
title="Source Credibility Distribution",
labels={'x': 'Credibility Score', 'y': 'Number of Sources'},
color_discrete_sequence=['#64B5F6']
)
fig_credibility.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
font_color='white'
)
visualizations.append({
'type': 'credibility_distribution',
'title': 'Source Credibility Analysis',
'figure': fig_credibility,
'description': 'Distribution of credibility scores across analyzed sources'
})
# Domain analysis
domains = {}
for result in results:
domain_type = 'edu' if '.edu' in result.domain else \
'gov' if '.gov' in result.domain else \
'org' if '.org' in result.domain else 'com'
domains[domain_type] = domains.get(domain_type, 0) + 1
if domains:
fig_domains = px.pie(
values=list(domains.values()),
names=list(domains.keys()),
title="Source Types Distribution",
color_discrete_sequence=['#64B5F6', '#42A5F5', '#2196F3', '#1976D2']
)
fig_domains.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
font_color='white'
)
visualizations.append({
'type': 'domain_distribution',
'title': 'Source Domain Analysis',
'figure': fig_domains,
'description': 'Breakdown of sources by domain type (educational, government, etc.)'
})
# Content length analysis
word_counts = [r.word_count for r in results if r.word_count > 0]
if word_counts:
fig_words = px.box(
y=word_counts,
title="Content Length Analysis",
labels={'y': 'Word Count'},
color_discrete_sequence=['#64B5F6']
)
fig_words.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
font_color='white'
)
visualizations.append({
'type': 'content_length',
'title': 'Content Depth Analysis',
'figure': fig_words,
'description': 'Distribution of content length across sources'
})
return visualizations
except Exception as e:
logger.error(f"Visualization generation failed: {e}")
return []
# Initialize the research engine
@st.cache_resource
def get_research_engine():
return ResearchEngine()
# --- 🎨 Enhanced UI Setup ---
st.set_page_config(
page_title="NexusQuery Pro - AI Research Engine",
layout="wide",
page_icon="🧠",
initial_sidebar_state="expanded"
)
# Professional Dark Theme CSS
st.markdown("""
<style>
/* Import professional fonts */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
/* Global dark theme */
.stApp {
background: linear-gradient(135deg, #0f1419 0%, #1a1f2e 100%);
color: #e2e8f0;
font-family: 'Inter', sans-serif;
}
/* Main header styling */
.main-header {
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-weight: 700;
font-size: 3rem;
text-align: center;
margin-bottom: 1rem;
text-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
}
.subtitle {
text-align: center;
color: #94a3b8;
font-size: 1.2rem;
font-weight: 400;
margin-bottom: 2rem;
line-height: 1.6;
}
/* Sidebar styling */
.css-1d391kg {
background-color: #1e293b;
border-right: 1px solid #334155;
}
/* Enhanced source boxes */
.source-box {
background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
border: 1px solid #475569;
border-radius: 12px;
padding: 1.5rem;
margin: 1rem 0;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.source-box::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 3px;
background: linear-gradient(90deg, #3b82f6, #1d4ed8);
border-radius: 12px 12px 0 0;
}
.source-box:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px -5px rgba(59, 130, 246, 0.2);
border-color: #3b82f6;
}
/* Citation styling */
.citation-number {
color: #3b82f6;
font-weight: 600;
font-size: 0.875rem;
vertical-align: super;
background: rgba(59, 130, 246, 0.1);
padding: 2px 4px;
border-radius: 3px;
margin: 0 2px;
}
/* Progress bars */
.stProgress > div > div > div {
background: linear-gradient(90deg, #3b82f6, #1d4ed8);
border-radius: 10px;
}
/* Buttons */
.stButton > button {
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white;
border: none;
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.3);
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px -5px rgba(59, 130, 246, 0.4);
}
/* Input fields */
.stTextInput input, .stSelectbox div div, .stSlider div div {
background-color: #1e293b !important;
border: 1px solid #475569 !important;
border-radius: 8px !important;
color: #e2e8f0 !important;
}
/* Metrics */
.metric-container {
background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
padding: 1.5rem;
border-radius: 12px;
border: 1px solid #475569;
text-align: center;
transition: all 0.3s ease;
}
.metric-container:hover {
border-color: #3b82f6;
box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}
.metric-value {
font-size: 2rem;
font-weight: 700;
color: #3b82f6;
display: block;
}
.metric-label {
color: #94a3b8;
font-size: 0.875rem;
text-transform: uppercase;
letter-spacing: 0.05em;
margin-top: 0.5rem;
}
/* Tabs */
.stTabs [data-baseweb="tab"] {
background-color: #1e293b;
color: #94a3b8;
border-radius: 8px 8px 0 0;
font-weight: 500;
}
.stTabs [data-baseweb="tab"]:hover {
background-color: #334155;
color: #e2e8f0;
}
.stTabs [aria-selected="true"] {
background-color: #3b82f6 !important;
color: white !important;
}
/* Expanders */
.streamlit-expanderHeader {
background-color: #1e293b;
color: #e2e8f0;
border-radius: 8px;
font-weight: 500;
}
/* Status indicators */
.status-indicator {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 8px;
}
.status-success { background-color: #10b981; }
.status-warning { background-color: #f59e0b; }
.status-error { background-color: #ef4444; }
.status-info { background-color: #3b82f6; }
/* Animations */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.fade-in-up {
animation: fadeInUp 0.6s ease-out;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #1e293b;
}
::-webkit-scrollbar-thumb {
background: #475569;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #64748b;
}
/* Footer */
.footer {
margin-top: 3rem;
padding: 2rem 0;
border-top: 1px solid #334155;
text-align: center;
color: #64748b;
}
/* Loading animation */
.loading-spinner {
border: 3px solid #334155;
border-top: 3px solid #3b82f6;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 0 auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
""", unsafe_allow_html=True)
# --- 📋 Header Section ---
st.markdown("""
<div class="fade-in-up">
<h1 class="main-header">🧠 NexusQuery Pro</h1>
<p class="subtitle">
Next-Generation AI Research Engine | Advanced Knowledge Synthesis with Real-Time Intelligence
<br>
<small>Powered by Gemini 2.0 Flash • Professional Research Analytics • Industry-Grade Insights</small>
</p>
</div>
""", unsafe_allow_html=True)
# --- 🎛️ Advanced Sidebar Configuration ---
with st.sidebar:
st.markdown("### ⚙️ Research Configuration")
# Research Mode
search_mode = st.selectbox(
"🎯 Intelligence Level",
["QuickSynth", "QuantumSynth", "OmniSynth"],
help="QuickSynth: Rapid insights (2-3 min) | QuantumSynth: Deep analysis (5-7 min) | OmniSynth: Comprehensive research (15+ min)",
index=1
)
# Advanced Research Features
st.markdown("### 🔬 Advanced Features")
col1, col2 = st.columns(2)
with col1:
executive_summary = st.checkbox("📄 Executive Summary", value=True)
future_insights = st.checkbox("🔮 Future Insights", value=True)
historical_context = st.checkbox("📚 Historical Context", value=False)
expert_quotes = st.checkbox("💬 Expert Quotes", value=True)
with col2:
perspective_toggle = st.checkbox("🔄 Multi-Perspective", value=True)
data_visualization = st.checkbox("📊 Data Visualization", value=True)
fact_check = st.checkbox("✅ Fact Verification", value=True)
semantic_analysis = st.checkbox("🧠 Semantic Analysis", value=False)
# Citation and Quality Controls
st.markdown("### 📖 Citation & Quality")
citation_style = st.selectbox(
"Citation Style",
["Inline Numbers", "Academic (APA)", "IEEE", "None"],
help="Choose your preferred citation format"
)
source_quality = st.select_slider(
"Source Quality Filter",
options=["Basic", "Enhanced", "Premium", "Academic"],
value="Enhanced",
help="Higher levels prioritize more credible sources"
)
# Search Parameters
st.markdown("### 🔍 Search Parameters")
source_count = st.slider(
"Sources to Analyze",
min_value=10,
max_value=100,
value=25,
help="More sources = more comprehensive analysis"
)
content_depth = st.select_slider(
"Content Analysis Depth",
options=["Surface", "Moderate", "Deep", "Comprehensive"],
value="Deep",
help="Determines how thoroughly each source is analyzed"
)
# Performance Settings
st.markdown("### ⚡ Performance")
parallel_processing = st.checkbox("🔄 Parallel Processing", value=True, help="Faster analysis using multiple threads")
real_time_updates = st.checkbox("📡 Real-Time Updates", value=True, help="Show progress as research proceeds")
# Research Analytics
st.markdown("### 📊 Analytics Dashboard")
if st.button("📈 View Research History"):
st.info("Research history feature coming soon!")
# Export Options
st.markdown("### 💾 Export Options")
export_format = st.selectbox(
"Export Format",
["Plain Text", "Markdown", "JSON", "PDF Report"],
index=1
)
st.divider()
# System Status
st.markdown("### 🔧 System Status")
col1, col2 = st.columns(2)
with col1:
st.markdown('<span class="status-indicator status-success"></span> API Connected', unsafe_allow_html=True)
st.markdown('<span class="status-indicator status-success"></span> Cache Ready', unsafe_allow_html=True)
with col2:
st.markdown('<span class="status-indicator status-info"></span> AI Model: Active', unsafe_allow_html=True)
st.markdown('<span class="status-indicator status-success"></span> Search: Optimal', unsafe_allow_html=True)
st.markdown(f"<small>Last Updated: {datetime.now().strftime('%H:%M:%S')}</small>", unsafe_allow_html=True)
# --- 🔍 Main Search Interface ---
st.markdown("### 🔍 Research Query Interface")
col1, col2 = st.columns([3, 1])
with col1:
query = st.text_input(
"",
placeholder="Enter your research question (e.g., 'Latest developments in quantum computing for healthcare applications')",
help="Be specific for better results. Include context, time frames, or particular aspects you're interested in."
)
with col2:
st.markdown("<br>", unsafe_allow_html=True)
search_button = st.button("🚀 Launch Research", use_container_width=True, type="primary")
# Research suggestions
if not query:
st.markdown("### 💡 Research Suggestions")
suggestion_cols = st.columns(3)
suggestions = [
("🧬 Biotech", "CRISPR gene editing latest clinical trials 2024"),
("🤖 AI/ML", "Large language models impact on software development"),
("🌱 Sustainability", "Carbon capture technology commercial viability"),
("💰 FinTech", "Cryptocurrency regulation global trends 2024"),
("🚗 Transportation", "Autonomous vehicle safety statistics latest research"),
("🏥 Healthcare", "Telemedicine effectiveness post-pandemic studies")
]
for i, (icon_topic, suggestion) in enumerate(suggestions):
with suggestion_cols[i % 3]:
if st.button(f"{icon_topic}", key=f"suggestion_{i}", help=suggestion):
st.session_state.suggested_query = suggestion
st.rerun()
# Handle suggested query
if hasattr(st.session_state, 'suggested_query'):
query = st.session_state.suggested_query
del st.session_state.suggested_query
st.rerun()
# Display research mode info
if query and not search_button:
mode_info = {
"QuickSynth": "⚡ Fast synthesis optimized for rapid insights and key findings",
"QuantumSynth": "🔄 Balanced analysis with multiple perspectives and detailed exploration",
"OmniSynth": "🌌 Comprehensive research with expert-level depth and academic rigor"
}
st.info(f"{mode_info[search_mode]} | Analyzing {source_count} sources with {content_depth.lower()} analysis")
# --- 🚀 Main Research Processing ---
if search_button and query:
try:
research_engine = get_research_engine()
# Create research configuration
config = ResearchConfig(
search_mode=search_mode,
source_count=source_count,
citation_style=citation_style,
include_perspectives=perspective_toggle,
future_insights=future_insights,
data_visualization=data_visualization,
executive_summary=executive_summary,
historical_context=historical_context,
expert_quotes=expert_quotes,
fact_check=fact_check,
semantic_analysis=semantic_analysis,
competitive_analysis=False
)
# Create main research interface
research_tab, sources_tab, analytics_tab, export_tab = st.tabs([
"🔬 Research Results",
"📚 Source Analysis",
"📊 Analytics Dashboard",
"💾 Export & Share"
])
with research_tab:
# Progress tracking
progress_container = st.container()
result_container = st.container()
with progress_container:
st.markdown("### 🔄 Research Progress")
progress_col1, progress_col2, progress_col3 = st.columns([2, 1, 1])
with progress_col1:
progress_bar = st.progress(0)
status_text = st.empty()
with progress_col2:
sources_found = st.empty()
with progress_col3:
time_elapsed = st.empty()
# Research metrics
metrics_placeholder = st.empty()
# Phase 1: Search and Discovery
start_time = datetime.now()
status_text.markdown('<span class="status-indicator status-info"></span> **Initiating search algorithms...**', unsafe_allow_html=True)
for i in range(0, 15):
progress_bar.progress(i)
time.sleep(0.1)
status_text.markdown('<span class="status-indicator status-success"></span> **Discovering relevant sources...**', unsafe_allow_html=True)
search_results = research_engine.enhanced_search(query, source_count)
sources_found.metric("Sources Found", len(search_results))
for i in range(15, 30):
progress_bar.progress(i)
time.sleep(0.05)
# Phase 2: Content Extraction
status_text.markdown('<span class="status-indicator status-info"></span> **Extracting and analyzing content...**', unsafe_allow_html=True)
if parallel_processing and len(search_results) > 5:
search_results = research_engine.extract_content_parallel(search_results, max_workers=5)
else:
for idx, result in enumerate(search_results[:10]): # Limit for sequential processing
try:
result.content = research_engine.fetch_content_advanced(result.url)
result.word_count = len(result.content.split())
# Update progress
progress = 30 + int((idx + 1) / min(len(search_results), 10) * 25)
progress_bar.progress(progress)
if real_time_updates:
time_elapsed.metric("Time Elapsed", f"{(datetime.now() - start_time).seconds}s")
except Exception as e:
logger.warning(f"Failed to process source {idx + 1}: {e}")
continue
# Phase 3: Quality Analysis
status_text.markdown('<span class="status-indicator status-info"></span> **Performing quality assessment...**', unsafe_allow_html=True)
high_quality_sources = []
total_words = 0
sentiment_analysis = {}
for result in search_results:
if result.content and len(result.content) > 100:
# Recalculate credibility with content
result.credibility_score = research_engine.calculate_credibility_score(result.url, result.content)
# Sentiment analysis
if semantic_analysis:
analysis = research_engine.analyze_sentiment_and_bias(result.content)
result.sentiment = analysis['sentiment']
sentiment_analysis[result.id] = analysis
total_words += result.word_count
high_quality_sources.append(result)
# Filter by quality level
quality_threshold = {'Basic': 0.3, 'Enhanced': 0.5, 'Premium': 0.7, 'Academic': 0.8}
filtered_sources = [s for s in high_quality_sources if s.credibility_score >= quality_threshold[source_quality]]
for i in range(55, 70):
progress_bar.progress(i)
time.sleep(0.05)
# Update metrics
with metrics_placeholder:
met_col1, met_col2, met_col3, met_col4 = st.columns(4)
with met_col1:
st.markdown(f"""
<div class="metric-container">
<span class="metric-value">{len(filtered_sources)}</span>
<span class="metric-label">Quality Sources</span>
</div>
""", unsafe_allow_html=True)
with met_col2:
avg_credibility = sum(s.credibility_score for s in filtered_sources) / max(len(filtered_sources), 1)
st.markdown(f"""
<div class="metric-container">
<span class="metric-value">{avg_credibility:.2f}</span>
<span class="metric-label">Avg Credibility</span>
</div>
""", unsafe_allow_html=True)
with met_col3:
st.markdown(f"""
<div class="metric-container">
<span class="metric-value">{total_words:,}</span>
<span class="metric-label">Words Analyzed</span>
</div>
""", unsafe_allow_html=True)
with met_col4:
processing_time = (datetime.now() - start_time).seconds
st.markdown(f"""
<div class="metric-container">
<span class="metric-value">{processing_time}s</span>
<span class="metric-label">Processing Time</span>
</div>
""", unsafe_allow_html=True)
# Phase 4: AI Analysis and Synthesis
status_text.markdown('<span class="status-indicator status-info"></span> **Synthesizing insights with AI...**', unsafe_allow_html=True)
# Prepare comprehensive context for AI
research_context = f"""
RESEARCH QUERY: {query}
RESEARCH MODE: {search_mode}
ANALYSIS DATE: {datetime.now().strftime("%B %d, %Y")}
SOURCES ANALYZED: {len(filtered_sources)}
TOTAL CONTENT WORDS: {total_words:,}
SOURCE DETAILS:
"""
for idx, source in enumerate(filtered_sources[:20]): # Limit context size
research_context += f"""
--- SOURCE {idx + 1} ---
Title: {source.title}
URL: {source.url}
Domain: {source.domain}
Credibility Score: {source.credibility_score}
Word Count: {source.word_count}
Content Preview: {source.content[:500]}...
"""
# Build advanced prompt based on configuration
feature_instructions = []
if config.executive_summary:
if search_mode == "QuickSynth":
feature_instructions.append("Begin with a concise Executive Summary (3-4 sentences) highlighting key findings and direct answers to the query.")
elif search_mode == "QuantumSynth":
feature_instructions.append("Start with a comprehensive Executive Summary (100-150 words) providing overview of findings, key insights, and implications.")
else: # OmniSynth
feature_instructions.append("Begin with an extensive Abstract (200-300 words) covering research scope, methodology, key findings, limitations, and conclusions.")
if config.future_insights:
feature_instructions.append("Include a dedicated 'Future Outlook' section discussing emerging trends, potential developments, predictions, and their timeline/probability.")
if config.historical_context:
feature_instructions.append("Provide historical context section tracing the evolution of the topic, key milestones, and how past developments inform current understanding.")
if config.expert_quotes: