SanketAI commited on
Commit
08b01aa
Β·
verified Β·
1 Parent(s): e85e581

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +276 -276
app.py CHANGED
@@ -1,277 +1,277 @@
1
- import streamlit as st
2
- import os
3
- import sys
4
- from typing import Tuple, List, Dict, Optional
5
- from router import Router
6
-
7
- sys.path.append(os.path.dirname(os.path.abspath(__file__)))
8
-
9
- class AcademicResearchAssistant:
10
- def __init__(self):
11
-
12
- self.router = Router()
13
- self.setup_streamlit_config()
14
- self.initialize_session_state()
15
-
16
- def setup_streamlit_config(self):
17
-
18
- st.set_page_config(
19
- page_title="Academic Research Assistant",
20
- page_icon="πŸ“š",
21
- layout="wide",
22
- initial_sidebar_state="expanded",
23
- menu_items={
24
- 'Get Help': 'https://github.com/yourusername/academic-research-assistant',
25
- 'Report a bug': "https://github.com/yourusername/academic-research-assistant/issues",
26
- 'About': "# Academic Research Assistant v1.0\nYour intelligent research companion."
27
- }
28
- )
29
-
30
- # Custom CSS to enhance the UI
31
- st.markdown("""
32
- <style>
33
- .stApp {
34
- background: linear-gradient(to bottom right, #f5f7fa, #eef2f7);
35
- }
36
- .stButton>button {
37
- background-color: #1f4287;
38
- color: white;
39
- border-radius: 5px;
40
- padding: 0.5rem 1rem;
41
- }
42
- .stProgress .st-bo {
43
- background-color: #1f4287;
44
- }
45
- .chat-message {
46
- padding: 10px;
47
- border-radius: 5px;
48
- margin: 5px 0;
49
- animation: fadeIn 0.5s ease-in;
50
- }
51
- .user-message {
52
- background-color: #e6f3ff;
53
- }
54
- .bot-message {
55
- background-color: #f0f2f6;
56
- }
57
- @keyframes fadeIn {
58
- from {opacity: 0;}
59
- to {opacity: 1;}
60
- }
61
- .paper-card {
62
- background-color: white;
63
- padding: 1.5rem;
64
- border-radius: 10px;
65
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
66
- margin-bottom: 1rem;
67
- }
68
- .paper-title {
69
- color: #1f4287;
70
- font-size: 1.1rem;
71
- font-weight: bold;
72
- margin-bottom: 0.5rem;
73
- }
74
- .paper-metadata {
75
- font-size: 0.9rem;
76
- color: #666;
77
- margin-bottom: 0.5rem;
78
- }
79
- .paper-abstract {
80
- font-size: 0.95rem;
81
- line-height: 1.5;
82
- margin-top: 1rem;
83
- padding-left: 1rem;
84
- border-left: 3px solid #1f4287;
85
- }
86
- .download-button {
87
- background-color: #4CAF50;
88
- color: white;
89
- padding: 0.5rem 1rem;
90
- border-radius: 5px;
91
- text-decoration: none;
92
- display: inline-block;
93
- margin-top: 1rem;
94
- }
95
- .metric-card {
96
- background-color: white;
97
- padding: 1rem;
98
- border-radius: 8px;
99
- box-shadow: 0 2px 4px rgba(0,0,0,0.05);
100
- text-align: center;
101
- }
102
- </style>
103
- """, unsafe_allow_html=True)
104
-
105
- def initialize_session_state(self):
106
-
107
- if "chat_history" not in st.session_state:
108
- st.session_state.chat_history = []
109
- if "fetched_papers" not in st.session_state:
110
- st.session_state.fetched_papers = []
111
- if "search_count" not in st.session_state:
112
- st.session_state.search_count = 0
113
- if "total_searches" not in st.session_state:
114
- st.session_state.total_searches = 0
115
-
116
- def display_welcome_message(self):
117
-
118
- st.title("πŸ“š Academic Research Paper Assistant")
119
-
120
- # Create three columns for metrics
121
- col1, col2, col3, col4 = st.columns([2, 1, 1, 1])
122
-
123
- with col1:
124
- st.markdown("""
125
- Welcome to your intelligent research companion! This tool helps you:
126
- - πŸ” Find relevant academic papers
127
- - πŸ“Š Analyze research trends
128
- - πŸ“– Access paper summaries
129
- - πŸ“₯ Download full papers
130
- """)
131
-
132
- # Display metrics in cards
133
- with col3:
134
- st.markdown("""
135
- <div class="metric-card">
136
- <h3>Papers Found</h3>
137
- <h2>{}</h2>
138
- </div>
139
- """.format(len(st.session_state.fetched_papers)), unsafe_allow_html=True)
140
-
141
- with col4:
142
- st.markdown("""
143
- <div class="metric-card">
144
- <h3>Total Searches</h3>
145
- <h2>{}</h2>
146
- </div>
147
- """.format(st.session_state.total_searches), unsafe_allow_html=True)
148
-
149
-
150
-
151
- def create_chat_interface(self) -> Tuple[str, bool]:
152
-
153
- with st.container():
154
- st.write("### πŸ’¬ Research Query Interface")
155
-
156
- # Create columns for better layout
157
- col1, col2 = st.columns([4, 1])
158
-
159
- with col1:
160
- user_input = st.text_input(
161
- "Enter your research query (e.g., 'Recent advances in quantum computing')",
162
- key="user_input",
163
- placeholder="Type your research question here...",
164
- max_chars=500
165
- )
166
-
167
- col3, col4, col5 = st.columns([2, 1, 1])
168
- with col3:
169
- send_button = st.button("πŸ” Search ", use_container_width=True)
170
- with col4:
171
- clear_button = st.button("πŸ—‘οΈ Clear History", use_container_width=True)
172
-
173
- if clear_button:
174
- st.session_state.chat_history = []
175
- st.session_state.fetched_papers = []
176
- st.session_state.search_count = 0
177
- st.session_state.total_searches = 0
178
- st.rerun()
179
-
180
- return user_input, send_button
181
-
182
- def process_user_input(self, user_input: str):
183
-
184
- with st.spinner('πŸ” Working on response...'):
185
- # Update search metrics
186
- st.session_state.search_count = len(st.session_state.fetched_papers)
187
- st.session_state.total_searches += 1
188
-
189
- try:
190
- # Get response from router
191
- response, papers = self.router.route_query(user_input)
192
-
193
- # Update papers in session state
194
- if papers:
195
- unique_papers = {paper['paper_number']: paper for paper in papers}
196
- st.session_state.fetched_papers = list(unique_papers.values())
197
-
198
- # Add bot response and use message to chat history
199
- if response:
200
- st.session_state.chat_history.append(("Bot", response))
201
- st.session_state.chat_history.append(("User", user_input))
202
- else:
203
- st.session_state.chat_history.append(
204
- ("Bot", "I couldn't find relevant papers for your query. Please try rephrasing or use more specific terms.")
205
- )
206
- except Exception as e:
207
- st.session_state.chat_history.append(
208
- ("Bot", f"An error occurred while processing your request: {str(e)}")
209
- )
210
- st.error("There was an error processing your request. Please try again.")
211
-
212
- def display_chat_history(self):
213
- """Display the chat history with user and bot messages"""
214
- for sender, message in reversed(st.session_state.chat_history):
215
- if sender == "User":
216
- st.markdown(
217
- "<div class='chat-message user-message'>"
218
- f"<strong>πŸ‘€ You:</strong> {message}"
219
- "</div>",
220
- unsafe_allow_html=True
221
- )
222
- else:
223
- st.markdown(
224
- "<div class='chat-message bot-message'>"
225
- f"<strong>πŸ€– Assistant:</strong> {message[0]}"
226
- "</div>",
227
- unsafe_allow_html=True
228
- )
229
-
230
- def display_papers(self):
231
- """Display the list of fetched papers with download links"""
232
- st.write("### πŸ“„ Retrieved Research Papers")
233
- if st.session_state.fetched_papers:
234
- for paper in st.session_state.fetched_papers:
235
- with st.expander(f"πŸ“‘ {paper.get('title', 'Untitled Paper')}"):
236
- st.markdown(
237
- "<div class='paper-card'>"
238
- f"<div class='paper-title'>{paper.get('title', '').replace('\n', ' ').strip()}</div>"
239
- f"<div class='paper-metadata'>Year: {paper.get('year', 'N/A')} | Paper ID: {paper.get('paper_number', 'N/A')}</div>"
240
- f"""{'<div class="paper-abstract">' + paper.get('abstract', '') + '</div>' if paper.get('abstract') else ''}"""
241
- "</div>",
242
- unsafe_allow_html=True
243
- )
244
-
245
- download_link = paper.get('link')
246
- if download_link:
247
- st.markdown(f"[πŸ“₯ Download PDF]({download_link})")
248
- else:
249
- st.warning("⚠️ No download link available")
250
- else:
251
- st.info("πŸ” No papers fetched yet. Start by entering a research query above!")
252
-
253
- def run(self):
254
- """Main method to run the application"""
255
- self.display_welcome_message()
256
-
257
-
258
- user_input, send_button = self.create_chat_interface()
259
-
260
- st.markdown("### πŸ’¬ Chat History")
261
- self.display_chat_history()
262
-
263
-
264
- if user_input and send_button:
265
- self.process_user_input(user_input)
266
- st.rerun()
267
-
268
- st.markdown("---")
269
- self.display_papers()
270
-
271
- def main():
272
-
273
- app = AcademicResearchAssistant()
274
- app.run()
275
-
276
- if __name__ == "__main__":
277
  main()
 
1
+ import streamlit as st
2
+ import os
3
+ import sys
4
+ from typing import Tuple, List, Dict, Optional
5
+ from router import Router
6
+
7
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
8
+
9
+ class AcademicResearchAssistant:
10
+ def __init__(self):
11
+
12
+ self.router = Router()
13
+ self.setup_streamlit_config()
14
+ self.initialize_session_state()
15
+
16
+ def setup_streamlit_config(self):
17
+
18
+ st.set_page_config(
19
+ page_title="Academic Research Assistant",
20
+ page_icon="πŸ“š",
21
+ layout="wide",
22
+ initial_sidebar_state="expanded",
23
+ menu_items={
24
+ 'Get Help': 'https://github.com/yourusername/academic-research-assistant',
25
+ 'Report a bug': "https://github.com/yourusername/academic-research-assistant/issues",
26
+ 'About': "# Academic Research Assistant v1.0\nYour intelligent research companion."
27
+ }
28
+ )
29
+
30
+ # Custom CSS to enhance the UI
31
+ st.markdown("""
32
+ <style>
33
+ .stApp {
34
+ background: linear-gradient(to bottom right, #f5f7fa, #eef2f7);
35
+ }
36
+ .stButton>button {
37
+ background-color: #1f4287;
38
+ color: white;
39
+ border-radius: 5px;
40
+ padding: 0.5rem 1rem;
41
+ }
42
+ .stProgress .st-bo {
43
+ background-color: #1f4287;
44
+ }
45
+ .chat-message {
46
+ padding: 10px;
47
+ border-radius: 5px;
48
+ margin: 5px 0;
49
+ animation: fadeIn 0.5s ease-in;
50
+ }
51
+ .user-message {
52
+ background-color: #e6f3ff;
53
+ }
54
+ .bot-message {
55
+ background-color: #f0f2f6;
56
+ }
57
+ @keyframes fadeIn {
58
+ from {opacity: 0;}
59
+ to {opacity: 1;}
60
+ }
61
+ .paper-card {
62
+ background-color: white;
63
+ padding: 1.5rem;
64
+ border-radius: 10px;
65
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
66
+ margin-bottom: 1rem;
67
+ }
68
+ .paper-title {
69
+ color: #1f4287;
70
+ font-size: 1.1rem;
71
+ font-weight: bold;
72
+ margin-bottom: 0.5rem;
73
+ }
74
+ .paper-metadata {
75
+ font-size: 0.9rem;
76
+ color: #666;
77
+ margin-bottom: 0.5rem;
78
+ }
79
+ .paper-abstract {
80
+ font-size: 0.95rem;
81
+ line-height: 1.5;
82
+ margin-top: 1rem;
83
+ padding-left: 1rem;
84
+ border-left: 3px solid #1f4287;
85
+ }
86
+ .download-button {
87
+ background-color: #4CAF50;
88
+ color: white;
89
+ padding: 0.5rem 1rem;
90
+ border-radius: 5px;
91
+ text-decoration: none;
92
+ display: inline-block;
93
+ margin-top: 1rem;
94
+ }
95
+ .metric-card {
96
+ background-color: white;
97
+ padding: 1rem;
98
+ border-radius: 8px;
99
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
100
+ text-align: center;
101
+ }
102
+ </style>
103
+ """, unsafe_allow_html=True)
104
+
105
+ def initialize_session_state(self):
106
+
107
+ if "chat_history" not in st.session_state:
108
+ st.session_state.chat_history = []
109
+ if "fetched_papers" not in st.session_state:
110
+ st.session_state.fetched_papers = []
111
+ if "search_count" not in st.session_state:
112
+ st.session_state.search_count = 0
113
+ if "total_searches" not in st.session_state:
114
+ st.session_state.total_searches = 0
115
+
116
+ def display_welcome_message(self):
117
+
118
+ st.title("πŸ“š Academic Research Paper Assistant")
119
+
120
+ # Create three columns for metrics
121
+ col1, col2, col3, col4 = st.columns([2, 1, 1, 1])
122
+
123
+ with col1:
124
+ st.markdown("""
125
+ Welcome to your intelligent research companion! This tool helps you:
126
+ - πŸ” Find relevant academic papers
127
+ - πŸ“Š Analyze research trends
128
+ - πŸ“– Access paper summaries
129
+ - πŸ“₯ Download full papers
130
+ """)
131
+
132
+ # Display metrics in cards
133
+ with col3:
134
+ st.markdown("""
135
+ <div class="metric-card">
136
+ <h3>Papers Found</h3>
137
+ <h2>{}</h2>
138
+ </div>
139
+ """.format(len(st.session_state.fetched_papers)), unsafe_allow_html=True)
140
+
141
+ with col4:
142
+ st.markdown("""
143
+ <div class="metric-card">
144
+ <h3>Total Searches</h3>
145
+ <h2>{}</h2>
146
+ </div>
147
+ """.format(st.session_state.total_searches), unsafe_allow_html=True)
148
+
149
+
150
+
151
+ def create_chat_interface(self) -> Tuple[str, bool]:
152
+
153
+ with st.container():
154
+ st.write("### πŸ’¬ Research Query Interface")
155
+
156
+ # Create columns for better layout
157
+ col1, col2 = st.columns([4, 1])
158
+
159
+ with col1:
160
+ user_input = st.text_input(
161
+ "Enter your research query (e.g., 'Recent advances in quantum computing')",
162
+ key="user_input",
163
+ placeholder="Type your research question here...",
164
+ max_chars=500
165
+ )
166
+
167
+ col3, col4, col5 = st.columns([2, 1, 1])
168
+ with col3:
169
+ send_button = st.button("πŸ” Search ", use_container_width=True)
170
+ with col4:
171
+ clear_button = st.button("πŸ—‘οΈ Clear History", use_container_width=True)
172
+
173
+ if clear_button:
174
+ st.session_state.chat_history = []
175
+ st.session_state.fetched_papers = []
176
+ st.session_state.search_count = 0
177
+ st.session_state.total_searches = 0
178
+ st.rerun()
179
+
180
+ return user_input, send_button
181
+
182
+ def process_user_input(self, user_input: str):
183
+
184
+ with st.spinner('πŸ” Working on response...'):
185
+ # Update search metrics
186
+ st.session_state.search_count = len(st.session_state.fetched_papers)
187
+ st.session_state.total_searches += 1
188
+
189
+ try:
190
+ # Get response from router
191
+ response, papers = self.router.route_query(user_input)
192
+
193
+ # Update papers in session state
194
+ if papers:
195
+ unique_papers = {paper['paper_number']: paper for paper in papers}
196
+ st.session_state.fetched_papers = list(unique_papers.values())
197
+
198
+ # Add bot response and use message to chat history
199
+ if response:
200
+ st.session_state.chat_history.append(("Bot", response))
201
+ st.session_state.chat_history.append(("User", user_input))
202
+ else:
203
+ st.session_state.chat_history.append(
204
+ ("Bot", "I couldn't find relevant papers for your query. Please try rephrasing or use more specific terms.")
205
+ )
206
+ except Exception as e:
207
+ st.session_state.chat_history.append(
208
+ ("Bot", f"An error occurred while processing your request: {str(e)}")
209
+ )
210
+ st.error("There was an error processing your request. Please try again.")
211
+
212
+ def display_chat_history(self):
213
+ """Display the chat history with user and bot messages"""
214
+ for sender, message in reversed(st.session_state.chat_history):
215
+ if sender == "User":
216
+ st.markdown(
217
+ "<div class='chat-message user-message'>"
218
+ f"<strong>πŸ‘€ You:</strong> {message}"
219
+ "</div>",
220
+ unsafe_allow_html=True
221
+ )
222
+ else:
223
+ st.markdown(
224
+ "<div class='chat-message bot-message'>"
225
+ f"<strong>πŸ€– Assistant:</strong> {message[0]}"
226
+ "</div>",
227
+ unsafe_allow_html=True
228
+ )
229
+
230
+ def display_papers(self):
231
+ """Display the list of fetched papers with download links"""
232
+ st.write("### πŸ“„ Retrieved Research Papers")
233
+ if st.session_state.fetched_papers:
234
+ for paper in st.session_state.fetched_papers:
235
+ with st.expander(f"πŸ“‘ {paper.get('title', 'Untitled Paper')}"):
236
+ st.markdown(
237
+ "<div class='paper-card'>"
238
+ f"<div class='paper-title'>{paper.get('title', '').replace('\n', ' ').strip()}</div>"
239
+ f"<div class='paper-metadata'>Year: {paper.get('year', 'N/A')} | Paper ID: {paper.get('paper_number', 'N/A')}</div>"
240
+ f"""{'<div class="paper-abstract">' + paper.get('abstract', '') + '</div>' if paper.get('abstract') else ''}"""
241
+ f"<{chr(92)}div>",
242
+ unsafe_allow_html=True
243
+ )
244
+
245
+ download_link = paper.get('link')
246
+ if download_link:
247
+ st.markdown(f"[πŸ“₯ Download PDF]({download_link})")
248
+ else:
249
+ st.warning("⚠️ No download link available")
250
+ else:
251
+ st.info("πŸ” No papers fetched yet. Start by entering a research query above!")
252
+
253
+ def run(self):
254
+ """Main method to run the application"""
255
+ self.display_welcome_message()
256
+
257
+
258
+ user_input, send_button = self.create_chat_interface()
259
+
260
+ st.markdown("### πŸ’¬ Chat History")
261
+ self.display_chat_history()
262
+
263
+
264
+ if user_input and send_button:
265
+ self.process_user_input(user_input)
266
+ st.rerun()
267
+
268
+ st.markdown("---")
269
+ self.display_papers()
270
+
271
+ def main():
272
+
273
+ app = AcademicResearchAssistant()
274
+ app.run()
275
+
276
+ if __name__ == "__main__":
277
  main()