-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReSeArcH.py
More file actions
3720 lines (3173 loc) · 165 KB
/
ReSeArcH.py
File metadata and controls
3720 lines (3173 loc) · 165 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
from datetime import datetime, timedelta
import base64
import os
import json
from tinydb import TinyDB, Query
import hashlib
import re
from collections import Counter
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from typing import List, Dict, Optional
import time
# Page configuration
st.set_page_config(
page_title="Bohrium | Science Navigator",
page_icon="🧪",
layout="wide",
initial_sidebar_state="expanded"
)
def set_app_background(image_file):
"""Sets the background of the Streamlit app to a local image file."""
if not os.path.exists(image_file):
st.error(f"Background image not found at '{image_file}'")
return
with open(image_file, "rb") as f:
img_bytes = f.read()
base64_img = base64.b64encode(img_bytes).decode()
st.markdown(f"""
<style>
.stApp {{
background-image: url("data:image/jpeg;base64,{base64_img}");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}}
</style>
""", unsafe_allow_html=True)
# Enhanced Custom CSS for styling
st.markdown("""
<style>
/* Sidebar styling */
[data-testid="stSidebar"] {
background: transparent !important;
backdrop-filter: blur(5px);
}
[data-testid="stSidebar"] > div:first-child {
background: transparent !important;
}
[data-testid="stHeader"] {
background: transparent !important;
}
/* BOHRIUM GREEN/GOLD THEME */
.stMarkdown, p, span, div, .stButton>button, .stTabs [data-baseweb="tab"] {
color: rgba(240, 240, 240, 0.9) !important;
}
.header-container {
background: rgba(10, 25, 20, 0.5);
backdrop-filter: blur(10px);
padding: 20px;
border-radius: 10px;
text-align: center;
margin-bottom: 30px;
border: 1px solid rgba(46, 204, 113, 0.2);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}
.header-title {
color: #ffffff;
font-size: 42px;
font-weight: bold;
margin: 0;
}
.header-subtitle {
color: rgba(220, 230, 225, 0.85);
font-size: 18px;
margin-top: 10px;
}
.tool-card {
background: rgba(20, 35, 30, 0.75);
backdrop-filter: blur(5px);
padding: 20px;
border-radius: 10px;
border: 1px solid rgba(46, 204, 113, 0.15);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
margin-bottom: 15px;
transition: transform 0.2s;
color: rgba(240, 240, 240, 0.9);
}
.tool-card:hover {
transform: translateY(-5px);
box-shadow: 0 4px 12px rgba(46, 204, 113, 0.3);
border: 1px solid rgba(46, 204, 113, 0.3);
}
.stTextInput > div > div > input {
border-radius: 25px;
border: 1px solid rgba(46, 204, 113, 0.6);
padding: 12px 20px;
background-color: rgba(10, 25, 20, 0.8);
color: rgba(240, 240, 240, 0.9);
}
.stButton > button {
border-radius: 25px;
background: transparent !important;
border: 1px solid rgba(46, 204, 113, 0.7) !important;
color: rgba(240, 240, 240, 0.9) !important;
padding: 10px 30px;
font-weight: bold;
transition: all 0.3s ease;
}
.stButton > button:hover {
background: rgba(46, 204, 113, 0.15) !important;
border-color: rgba(46, 204, 113, 1) !important;
color: #ffffff !important;
}
.stSelectbox > div > div {
background-color: rgba(10, 25, 20, 0.8);
border: 1px solid rgba(46, 204, 113, 0.4);
color: rgba(240, 240, 240, 0.9);
}
.stTextArea > div > div > textarea {
background-color: rgba(10, 25, 20, 0.8);
color: rgba(240, 240, 240, 0.9);
border: 1px solid rgba(46, 204, 113, 0.6);
}
.stNumberInput > div > div > input {
background-color: rgba(10, 25, 20, 0.8);
color: rgba(240, 240, 240, 0.9);
border: 1px solid rgba(46, 204, 113, 0.6);
}
.streamlit-expanderHeader {
background-color: rgba(20, 35, 30, 0.75);
border-radius: 5px;
color: rgba(240, 240, 240, 0.9);
}
.stTabs [data-baseweb="tab-list"] {
background-color: transparent;
border-bottom: 1px solid rgba(46, 204, 113, 0.3);
}
[data-testid="stMetricValue"] {
color: #2ecc71;
}
.caption {
color: rgba(180, 200, 190, 0.7) !important;
}
[data-testid="stSidebar"] * {
color: rgba(240, 240, 240, 0.9) !important;
}
hr {
border-color: rgba(46, 204, 113, 0.2);
}
.nobel-banner {
background: transparent !important;
padding: 10px;
border-radius: 8px;
text-align: center;
margin-bottom: 20px;
font-weight: bold;
color: rgba(240, 240, 240, 0.9) !important;
box-shadow: none !important;
}
.accuracy-badge {
background: rgba(46, 204, 113, 0.2);
border: 1px solid rgba(46, 204, 113, 0.7);
color: white;
padding: 5px 15px;
border-radius: 20px;
display: inline-block;
font-weight: bold;
font-size: 14px;
margin-top: 10px;
}
/* Advanced Feature Cards */
.feature-card {
background: rgba(20, 35, 30, 0.85);
backdrop-filter: blur(8px);
padding: 25px;
border-radius: 15px;
border: 1px solid rgba(46, 204, 113, 0.25);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
margin: 15px 0;
transition: all 0.3s ease;
}
.feature-card:hover {
border-color: rgba(46, 204, 113, 0.5);
box-shadow: 0 6px 20px rgba(46, 204, 113, 0.2);
}
/* Citation Badge */
.citation-badge {
background: rgba(46, 204, 113, 0.15);
border: 1px solid rgba(46, 204, 113, 0.5);
color: #2ecc71;
padding: 3px 10px;
border-radius: 12px;
font-size: 12px;
font-weight: bold;
}
/* Impact Score */
.impact-score {
background: linear-gradient(135deg, rgba(46, 204, 113, 0.2), rgba(255, 215, 0, 0.2));
border: 1px solid rgba(46, 204, 113, 0.6);
padding: 15px;
border-radius: 10px;
text-align: center;
}
/* Research Timeline */
.timeline-item {
border-left: 2px solid rgba(46, 204, 113, 0.5);
padding-left: 20px;
margin: 15px 0;
position: relative;
}
.timeline-item::before {
content: "●";
position: absolute;
left: -6px;
color: #2ecc71;
font-size: 12px;
}
/* Analysis Card */
.analysis-card {
background: rgba(15, 30, 25, 0.9);
border: 1px solid rgba(46, 204, 113, 0.3);
border-radius: 10px;
padding: 20px;
margin: 10px 0;
}
/* Progress Bar Custom */
.custom-progress {
background: rgba(46, 204, 113, 0.2);
height: 8px;
border-radius: 4px;
overflow: hidden;
}
.custom-progress-fill {
background: linear-gradient(90deg, #2ecc71, #27ae60);
height: 100%;
transition: width 0.3s ease;
}
/* Alert Box */
.alert-success {
background: rgba(46, 204, 113, 0.15);
border-left: 4px solid #2ecc71;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
.alert-info {
background: rgba(52, 152, 219, 0.15);
border-left: 4px solid #3498db;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
/* Badge Container */
.badge-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 15px 0;
}
.topic-badge {
background: rgba(46, 204, 113, 0.2);
border: 1px solid rgba(46, 204, 113, 0.5);
padding: 5px 12px;
border-radius: 15px;
font-size: 13px;
color: #2ecc71;
}
</style>
""", unsafe_allow_html=True)
# Set the background image
image_path = "green-gradient-abstract-background-empty-room-with-space-your-text-picture.jpg"
set_app_background(image_path)
# Advanced Analytics Class
class ResearchAnalytics:
"""Advanced analytics for research patterns and insights"""
@staticmethod
def calculate_h_index(citations: List[int]) -> int:
"""Calculate h-index from citation counts"""
if not citations:
return 0
citations_sorted = sorted(citations, reverse=True)
h = 0
for i, c in enumerate(citations_sorted):
if c >= i + 1:
h = i + 1
else:
break
return h
@staticmethod
def calculate_impact_factor(papers: List[Dict]) -> float:
"""Calculate a simplified impact factor"""
if not papers:
return 0.0
total_citations = sum(p.get('citations', 0) for p in papers)
return round(total_citations / len(papers), 2)
@staticmethod
def extract_keywords(text: str, top_n: int = 10) -> List[str]:
"""Extract top keywords from text"""
# Simple keyword extraction
words = re.findall(r'\b[a-z]{4,}\b', text.lower())
common_words = {'that', 'this', 'with', 'from', 'have', 'been', 'their', 'which', 'about', 'would'}
words = [w for w in words if w not in common_words]
word_freq = Counter(words)
return [word for word, _ in word_freq.most_common(top_n)]
@staticmethod
def calculate_research_velocity(papers: List[Dict]) -> Dict:
"""Calculate research output velocity"""
if not papers:
return {"papers_per_month": 0, "trend": "stable"}
# Group by month
monthly_counts = {}
for paper in papers:
date_str = paper.get('date', '')
if date_str:
try:
month = date_str[:7] # YYYY-MM
monthly_counts[month] = monthly_counts.get(month, 0) + 1
except:
pass
if len(monthly_counts) < 2:
return {"papers_per_month": len(papers), "trend": "stable"}
avg = sum(monthly_counts.values()) / len(monthly_counts)
recent = list(monthly_counts.values())[-3:]
recent_avg = sum(recent) / len(recent) if recent else avg
trend = "increasing" if recent_avg > avg * 1.2 else "decreasing" if recent_avg < avg * 0.8 else "stable"
return {
"papers_per_month": round(avg, 2),
"trend": trend,
"recent_average": round(recent_avg, 2)
}
# Citation Network Builder
class CitationNetwork:
"""Build and analyze citation networks"""
def __init__(self):
self.nodes = {}
self.edges = []
def add_paper(self, paper_id: str, title: str, citations: List[str]):
"""Add a paper to the network"""
self.nodes[paper_id] = {
'title': title,
'citations': citations,
'cited_by': []
}
for cited_id in citations:
self.edges.append((paper_id, cited_id))
if cited_id in self.nodes:
self.nodes[cited_id]['cited_by'].append(paper_id)
def get_central_papers(self, top_n: int = 10) -> List[tuple]:
"""Get most central papers by citation count"""
paper_scores = []
for paper_id, data in self.nodes.items():
score = len(data.get('cited_by', []))
paper_scores.append((paper_id, data['title'], score))
return sorted(paper_scores, key=lambda x: x[2], reverse=True)[:top_n]
def find_research_clusters(self) -> Dict:
"""Identify research clusters"""
# Simple clustering based on citation overlap
clusters = {}
for paper_id, data in self.nodes.items():
citations = set(data['citations'])
assigned = False
for cluster_id, cluster_papers in clusters.items():
overlap = sum(1 for p in cluster_papers if set(self.nodes.get(p, {}).get('citations', [])) & citations)
if overlap > len(citations) * 0.3: # 30% overlap threshold
clusters[cluster_id].append(paper_id)
assigned = True
break
if not assigned:
clusters[f"cluster_{len(clusters)}"] = [paper_id]
return clusters
# Smart Search Engine
class SmartSearchEngine:
"""Advanced search with semantic understanding"""
@staticmethod
def parse_advanced_query(query: str) -> Dict:
"""Parse advanced search syntax"""
parsed = {
'terms': [],
'authors': [],
'year_range': None,
'journals': [],
'exclude': [],
'field': None
}
# Extract authors
author_pattern = r'author:(\w+(?:\s+\w+)?)'
authors = re.findall(author_pattern, query, re.IGNORECASE)
parsed['authors'] = authors
query = re.sub(author_pattern, '', query, flags=re.IGNORECASE)
# Extract year range
year_pattern = r'year:(\d{4})-(\d{4})'
year_match = re.search(year_pattern, query)
if year_match:
parsed['year_range'] = (int(year_match.group(1)), int(year_match.group(2)))
query = re.sub(year_pattern, '', query)
# Extract journals
journal_pattern = r'journal:(["\']?)([^"\']+)\1'
journals = re.findall(journal_pattern, query, re.IGNORECASE)
parsed['journals'] = [j[1] for j in journals]
query = re.sub(journal_pattern, '', query, flags=re.IGNORECASE)
# Extract exclusions
exclude_pattern = r'-(\w+)'
excludes = re.findall(exclude_pattern, query)
parsed['exclude'] = excludes
query = re.sub(exclude_pattern, '', query)
# Extract field
field_pattern = r'field:(\w+)'
field_match = re.search(field_pattern, query, re.IGNORECASE)
if field_match:
parsed['field'] = field_match.group(1)
query = re.sub(field_pattern, '', query, flags=re.IGNORECASE)
# Remaining terms
parsed['terms'] = [t.strip() for t in query.split() if t.strip()]
return parsed
@staticmethod
def suggest_related_queries(query: str) -> List[str]:
"""Generate related search suggestions"""
base_terms = query.lower().split()
suggestions = []
expansions = {
'quantum': ['quantum computing', 'quantum mechanics', 'quantum entanglement'],
'machine': ['machine learning', 'deep learning', 'neural networks'],
'gene': ['gene editing', 'gene therapy', 'genetic engineering'],
'cancer': ['cancer treatment', 'oncology', 'tumor biology'],
'climate': ['climate change', 'global warming', 'climate modeling']
}
for term in base_terms:
if term in expansions:
suggestions.extend(expansions[term])
if not suggestions:
suggestions = [
f"{query} review",
f"{query} recent advances",
f"{query} applications",
f"{query} methodology"
]
return suggestions[:5]
# Collaboration Recommender
class CollaborationRecommender:
"""Recommend potential collaborators"""
@staticmethod
def find_potential_collaborators(user_interests: List[str], researcher_db: List[Dict]) -> List[Dict]:
"""Find researchers with overlapping interests"""
matches = []
user_set = set(i.lower() for i in user_interests)
for researcher in researcher_db:
researcher_interests = set(i.lower() for i in researcher.get('interests', []))
overlap = len(user_set & researcher_interests)
if overlap > 0:
score = overlap / len(user_set) * 100
matches.append({
'name': researcher.get('name'),
'institution': researcher.get('institution'),
'overlap_score': round(score, 1),
'common_interests': list(user_set & researcher_interests)
})
return sorted(matches, key=lambda x: x['overlap_score'], reverse=True)[:10]
# Literature Review Generator
class LiteratureReviewGenerator:
"""Generate comprehensive literature reviews"""
@staticmethod
def generate_review_outline(topic: str, papers: List[Dict]) -> Dict:
"""Generate a structured review outline"""
outline = {
'introduction': f"Overview of {topic}",
'sections': [],
'methodology': "Research methodology and selection criteria",
'findings': "Key findings and trends",
'gaps': "Research gaps and future directions",
'conclusion': "Summary and implications"
}
# Group papers by themes
themes = {}
for paper in papers:
keywords = paper.get('keywords', [])
for keyword in keywords:
if keyword not in themes:
themes[keyword] = []
themes[keyword].append(paper)
# Create sections from themes
for theme, theme_papers in sorted(themes.items(), key=lambda x: len(x[1]), reverse=True)[:5]:
outline['sections'].append({
'title': theme.title(),
'papers': len(theme_papers),
'description': f"Analysis of {theme} in the context of {topic}"
})
return outline
@staticmethod
def synthesize_findings(papers: List[Dict]) -> Dict:
"""Synthesize findings from multiple papers"""
synthesis = {
'total_papers': len(papers),
'methodologies': Counter(),
'key_findings': [],
'controversies': [],
'consensus': []
}
for paper in papers:
method = paper.get('methodology', 'unknown')
synthesis['methodologies'][method] += 1
return synthesis
# Research Assistant AI
class ResearchAssistant:
"""AI-powered research assistant"""
def __init__(self, model):
self.model = model
self.context = []
def generate_research_questions(self, topic: str, num_questions: int = 5) -> List[str]:
"""Generate research questions for a topic"""
prompt = f"""Generate {num_questions} innovative research questions for the topic: {topic}
Requirements:
- Questions should be specific and testable
- Cover different aspects of the topic
- Range from fundamental to applied research
- Be clear and focused
Format: Return only the questions, numbered 1-{num_questions}"""
try:
response = self.model.generate_content(prompt)
questions = [q.strip() for q in response.text.split('\n') if q.strip() and q[0].isdigit()]
return questions[:num_questions]
except:
return [f"Research question {i+1} about {topic}" for i in range(num_questions)]
def generate_methodology(self, research_question: str) -> Dict:
"""Generate methodology for a research question"""
prompt = f"""Design a research methodology for the following question:
{research_question}
Include:
1. Study design
2. Data collection methods
3. Analysis approach
4. Expected outcomes
5. Potential limitations
Be specific and practical."""
try:
response = self.model.generate_content(prompt)
return {
'methodology': response.text,
'generated_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
except Exception as e:
return {'methodology': f"Error generating methodology: {str(e)}", 'generated_at': ''}
def critique_paper(self, paper_abstract: str) -> Dict:
"""Provide critical analysis of a paper"""
prompt = f"""Provide a critical analysis of this research abstract:
{paper_abstract}
Analyze:
1. Strengths of the research
2. Potential weaknesses or limitations
3. Methodological concerns
4. Significance and impact
5. Suggestions for improvement
Be constructive and specific."""
try:
response = self.model.generate_content(prompt)
return {
'critique': response.text,
'analysis_date': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
except Exception as e:
return {'critique': f"Error generating critique: {str(e)}", 'analysis_date': ''}
def suggest_experiments(self, hypothesis: str) -> List[Dict]:
"""Suggest experiments to test a hypothesis"""
prompt = f"""Suggest 3 experiments to test this hypothesis:
{hypothesis}
For each experiment, provide:
- Experiment design
- Required materials/equipment
- Procedure outline
- Expected results
- Controls needed
Format clearly with experiment numbers."""
try:
response = self.model.generate_content(prompt)
return [{
'description': response.text,
'generated_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}]
except Exception as e:
return [{'description': f"Error: {str(e)}", 'generated_at': ''}]
# Initialize session state with advanced features
# ... (starts around line 600)
if 'state_loaded' not in st.session_state:
db = TinyDB('bohrium_db.json')
user_data_table = db.table('user_data')
saved_data = user_data_table.get(doc_id=1)
if saved_data:
# Use this pattern to ensure lists
st.session_state.chat_history = saved_data.get('chat_history', []) if isinstance(saved_data.get('chat_history'), list) else []
st.session_state.current_tool = saved_data.get('current_tool', 'Science Navigator')
st.session_state.library = saved_data.get('library', []) if isinstance(saved_data.get('library'), list) else []
st.session_state.search_history = saved_data.get('search_history', []) if isinstance(saved_data.get('search_history'), list) else []
st.session_state.collections = saved_data.get('collections', []) if isinstance(saved_data.get('collections'), list) else []
st.session_state.reading_list = saved_data.get('reading_list', []) if isinstance(saved_data.get('reading_list'), list) else []
st.session_state.notes = saved_data.get('notes', []) if isinstance(saved_data.get('notes'), list) else []
# This is the key line that prevents your error:
st.session_state.projects = saved_data.get('projects', []) if isinstance(saved_data.get('projects'), list) else []
st.session_state.annotations = saved_data.get('annotations', {}) if isinstance(saved_data.get('annotations'), dict) else {}
st.session_state.research_profile = saved_data.get('research_profile', {}) if isinstance(saved_data.get('research_profile'), dict) else {}
st.session_state.collaborations = saved_data.get('collaborations', []) if isinstance(saved_data.get('collaborations'), list) else []
st.session_state.experiments = saved_data.get('experiments', []) if isinstance(saved_data.get('experiments'), list) else []
st.session_state.hypotheses = saved_data.get('hypotheses', []) if isinstance(saved_data.get('hypotheses'), list) else []
st.session_state.data_sets = saved_data.get('data_sets', []) if isinstance(saved_data.get('data_sets'), list) else []
st.toast("Loaded saved session data.", icon="💾")
else:
st.session_state.chat_history = []
st.session_state.current_tool = 'Science Navigator'
st.session_state.library = []
st.session_state.search_history = []
st.session_state.collections = []
st.session_state.reading_list = []
st.session_state.notes = []
st.session_state.projects = [] # This is also correct
st.session_state.annotations = {}
st.session_state.research_profile = {
'interests': [],
'expertise_areas': [],
'h_index': 0,
'total_citations': 0,
'publications': []
}
st.session_state.collaborations = []
st.session_state.experiments = []
st.session_state.hypotheses = []
st.session_state.data_sets = []
st.session_state.state_loaded = True
# ... (rest of your file)
def save_state():
"""Saves the current session state to the database."""
db= TinyDB('bohrium_db.json')
user_data_table = db.table('user_data')
current_state = {
'chat_history': st.session_state.chat_history,
'current_tool': st.session_state.current_tool,
'library': st.session_state.library,
'search_history': st.session_state.search_history,
'collections': st.session_state.collections,
'reading_list': st.session_state.reading_list,
'notes': st.session_state.notes,
'projects': st.session_state.projects,
'annotations': st.session_state.annotations,
'research_profile': st.session_state.research_profile,
'collaborations': st.session_state.collaborations,
'experiments': st.session_state.experiments,
'hypotheses': st.session_state.hypotheses,
'data_sets': st.session_state.data_sets,
}
if user_data_table.get(doc_id=1):
user_data_table.update(current_state, doc_ids=[1])
else:
user_data_table.insert(current_state)
st.toast("Progress saved!", icon="💾")
# Configure Gemini API
try:
genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
model = genai.GenerativeModel('gemma-3-27b-it')
research_assistant = ResearchAssistant(model)
except Exception as e:
st.error("⚠️ Please configure GEMINI_API_KEY in Streamlit secrets")
research_assistant = None
# Password Protection
def check_password():
"""Returns `True` if the user has the correct password."""
def password_entered():
"""Checks whether a password entered by the user is correct."""
if st.session_state["password"] == st.secrets["password"]:
st.session_state["password_correct"] = True
del st.session_state["password"]
else:
st.session_state["password_correct"] = False
if "password_correct" not in st.session_state:
st.text_input("Password", type="password", on_change=password_entered, key="password")
return False
elif not st.session_state["password_correct"]:
st.text_input("Password", type="password", on_change=password_entered, key="password")
st.error("Password incorrect")
return False
else:
return True
if not check_password():
st.stop()
# Enhanced Sidebar Navigation
with st.sidebar:
st.markdown("### 🧭 Navigation")
# Main tools
menu_items = {
"🆕 New Chat": "new_chat",
"🔍 Academic Search": "academic_search",
"🌐 Explore": "explore",
"📋 Subscription": "subscription",
"📚 Library": "library",
"👨🎓 Scholars": "scholars",
"📖 Knowledge Base": "knowledge_base",
"🎯 Practice": "practice",
"🛠️ Uni-Lab": "uni_lab",
"💾 Computation": "computation",
"📊 History": "history",
"🔬 Research Projects": "projects",
"📈 Analytics": "analytics",
"🤝 Collaboration": "collaboration",
"🧬 Hypothesis Lab": "hypothesis_lab",
"📝 Literature Review": "lit_review",
"🎓 Citation Manager": "citations"
}
for label, key in menu_items.items():
if st.button(label, key=key, use_container_width=True):
st.session_state.current_tool = label
save_state()
st.markdown("---")
# Quick Stats
# Quick Stats
st.markdown("### 📊 Quick Stats")
# Add checks to prevent crash if state is not a list
papers_saved = 0
if isinstance(st.session_state.library, list):
papers_saved = len(st.session_state.library)
active_projects = 0
if isinstance(st.session_state.projects, list):
active_projects = len(st.session_state.projects)
notes_count = 0
if isinstance(st.session_state.notes, list):
notes_count = len(st.session_state.notes)
st.metric("Papers Saved", papers_saved)
st.metric("Active Projects", active_projects)
st.metric("Notes", notes_count)
st.markdown("---")
# Language selector
language = st.selectbox("🌐 Language", ["English", "中文", "Español", "Français", "Deutsch"])
st.markdown("---")
# Login button
if st.button("🔐 Log In", use_container_width=True, key="login_button"):
st.info("Login functionality would be implemented here.")
# Main content area
st.markdown('<div class="nobel-banner">🏆 Nobel 2025 Hub | Connect with the Great Minds and Explore Nobel Discoveries</div>', unsafe_allow_html=True)
# Header
st.markdown("""
<div class="header-container">
<div style="display: flex; align-items: center; justify-content: center;">
<span style="font-size: 60px; margin-right: 20px;">🧪</span>
<div>
<h1 class="header-title">Advanced Science Navigator</h1>
<p class="header-subtitle">AI-Powered Research Platform - Beyond Traditional Literature Search</p>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Main content based on selected tool
if st.session_state.current_tool in ["🆕 New Chat", "Science Navigator"]:
# Enhanced chat interface with AI capabilities
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
# Advanced search modes
search_mode = st.selectbox(
"Search Mode",
["💬 Conversational", "🔬 Deep Research", "📊 Data Analysis", "🎯 Focused Query", "🌐 Multi-Source"]
)
# Create columns for input and action buttons
input_col, btn1_col, btn2_col, btn3_col = st.columns([5, 1, 1, 1])
with input_col:
user_query = st.text_input(
"",
placeholder="Ask any scientific questions or use advanced syntax (author:, year:, field:)...",
key="main_search",
label_visibility="collapsed"
)
with btn1_col:
if st.button("⚡", help="Quick Answer", use_container_width=True):
st.session_state.query_mode = "quick"
with btn2_col:
if st.button("🔬", help="Deep Research", use_container_width=True):
st.session_state.query_mode = "deep"
with btn3_col:
if st.button("💡", help="AI Suggestions", use_container_width=True):
st.session_state.query_mode = "suggest"
if user_query:
# Parse advanced query
search_engine = SmartSearchEngine()
parsed_query = search_engine.parse_advanced_query(user_query)
# Show parsed query info
if parsed_query['authors'] or parsed_query['year_range'] or parsed_query['field']:
with st.expander("🔍 Advanced Query Detected"):
if parsed_query['authors']:
st.write(f"**Authors:** {', '.join(parsed_query['authors'])}")
if parsed_query['year_range']:
st.write(f"**Year Range:** {parsed_query['year_range'][0]} - {parsed_query['year_range'][1]}")
if parsed_query['field']:
st.write(f"**Field:** {parsed_query['field']}")
if parsed_query['exclude']:
st.write(f"**Excluding:** {', '.join(parsed_query['exclude'])}")
# Add to history
st.session_state.search_history.append({
"query": user_query,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"mode": search_mode
})
save_state()
# Generate response using Gemini
with st.spinner("🔍 Analyzing scientific literature with AI..."):
try:
# Enhanced prompt based on mode
if search_mode == "🔬 Deep Research":
prompt = f"""You are an expert scientific research assistant. Provide a comprehensive, in-depth analysis of:
Question: {user_query}
Include:
1. **Overview**: Brief introduction to the topic
2. **Current State of Research**: What do we know?
3. **Key Findings**: Major discoveries and breakthroughs
4. **Methodologies**: Common research approaches
5. **Controversies/Debates**: Areas of disagreement
6. **Future Directions**: Where is the field heading?
7. **Practical Applications**: Real-world implications
8. **Key Researchers**: Notable contributors to the field
Provide citations where possible and be scientifically rigorous."""
elif search_mode == "📊 Data Analysis":
prompt = f"""Analyze the following research query from a data-driven perspective:
Question: {user_query}
Provide:
1. **Statistical Overview**: Key numbers and trends
2. **Data Sources**: Where to find relevant datasets
3. **Analysis Methods**: Appropriate statistical/analytical approaches
4. **Visualization Suggestions**: How to present the data
5. **Common Pitfalls**: What to watch out for in analysis
6. **Tools & Software**: Recommended analysis tools
Be specific and actionable."""
elif search_mode == "🎯 Focused Query":
prompt = f"""Provide a focused, precise answer to:
{user_query}
Requirements:
- Be concise but complete
- Focus on the most important information
- Cite key sources
- Avoid unnecessary background
- Get straight to the answer"""
elif search_mode == "🌐 Multi-Source":
prompt = f"""Synthesize information from multiple perspectives on:
{user_query}
Include:
1. **Academic Perspective**: What researchers say
2. **Clinical/Applied Perspective**: Real-world applications
3. **Industry Perspective**: Commercial implications
4. **Public Policy Perspective**: Regulatory and societal aspects
5. **Interdisciplinary Connections**: Related fields
6. **Consensus vs. Debate**: Points of agreement and disagreement
Provide a balanced, multi-faceted view."""