forbiddensoul90 commited on
Commit
5d87899
β€’
1 Parent(s): f2da1f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +291 -291
app.py CHANGED
@@ -1,292 +1,292 @@
1
- import streamlit as st
2
- from typing import List, Dict, Any, Optional
3
- import asyncio
4
- from back import (ChatConfig, ChatLogger, ChatMemory, QuestionGenerator,
5
- GeminiRAG, ProductDatabase, UserManager, UserInfo)
6
- import os
7
-
8
- # UI Text in English
9
- UI_TEXT = {
10
- "welcome_message": """
11
- Welcome to the Career Guidance Chatbot! πŸŽ“
12
-
13
- Hi! We are here to help you navigate your career journey.
14
-
15
- Ask any questions you have about internships, placements, skills development, career paths, or anything else related to your future career.
16
-
17
- Choose a question below or ask your own.
18
- """,
19
- "input_placeholder": "Enter your question here...",
20
- "input_label": "Ask Anything:",
21
- "clear_chat": "Clear Chat",
22
- "sidebar_title": "Tell Us About Yourself for Personalized Guidance",
23
- "form_name": "Your Name",
24
- "form_college": "College Name",
25
- "form_degree": "Degree",
26
- "form_year": "Year of Study",
27
- "form_goals": "Your Career Goals",
28
- "form_internship": "Have you done an internship?",
29
- "form_placement": "Have you secured a placement?",
30
- "form_submit": "Get Personalized Advice",
31
- "form_success": "βœ… Personalized advice activated!",
32
- "form_error": "❌ Error saving information. Please try again.",
33
- "form_required": "Please fill in all required fields.",
34
- "initial_questions": [
35
- "What are some good career options in my field?",
36
- "How do I get an internship in my desired field?",
37
- "What skills are most important for success in this career path?",
38
- "What are some tips for preparing for job interviews?"
39
- ]
40
- }
41
-
42
- def init_session_state():
43
- """Initialize all session state variables"""
44
- defaults = {
45
- 'initialized': False,
46
- 'chat_memory': ChatMemory(),
47
- 'messages': [],
48
- 'message_counter': 0,
49
- 'processed_questions': set(),
50
- 'trigger_rerun': False,
51
- 'user_info': None,
52
- 'show_suggestions': False
53
- }
54
-
55
- for key, value in defaults.items():
56
- if key not in st.session_state:
57
- st.session_state[key] = value
58
-
59
- # Configure the page
60
- st.set_page_config(
61
- page_title="Career Guidance Chatbot",
62
- page_icon="πŸŽ“",
63
- layout="wide"
64
- )
65
-
66
- # Custom CSS
67
- st.markdown("""
68
- <style>
69
- .user-message {
70
- background-color: #98BF64;
71
- color: black;
72
- padding: 15px;
73
- border-radius: 15px;
74
- margin: 10px 0;
75
- }
76
- .assistant-message {
77
- background-color: #363E35;
78
- color: #98FB98;
79
- padding: 15px;
80
- border-radius: 15px;
81
- margin: 10px 0;
82
- }
83
- .stButton > button {
84
- background-color: #212B2A;
85
- color: white;
86
- border: none;
87
- padding: 10px 15px;
88
- border-radius: 5px;
89
- transition: background-color 0.3s;
90
- }
91
- .stButton > button:hover {
92
- background-color: #45a049;
93
- }
94
- </style>
95
- """, unsafe_allow_html=True)
96
-
97
- def initialize_components():
98
- """Initialize and cache application components"""
99
- try:
100
- config = ChatConfig()
101
- logger = ChatLogger(config.log_file)
102
- question_gen = QuestionGenerator(config.gemini_api_key)
103
- rag = GeminiRAG(config.gemini_api_key)
104
- user_manager = UserManager(config.user_data_file)
105
- return config, logger, question_gen, rag, user_manager
106
- except Exception as e:
107
- st.error(f"Error initializing components: {str(e)}")
108
- raise e
109
-
110
- def load_initial_database():
111
- """Load the default database"""
112
- if not st.session_state.initialized:
113
- try:
114
- config, logger, question_gen, rag, user_manager = initialize_components()
115
-
116
- db = ProductDatabase(config)
117
- # Here, you would process your markdown files to create the database
118
- # Replace 'path/to/your/markdown/files' with the actual path
119
- for filename in os.listdir("blogs"):
120
- if filename.endswith(".md"):
121
- with open(os.path.join("blogs", filename), "r", encoding="utf-8") as f:
122
- markdown_content = f.read()
123
- db.process_markdown(markdown_content)
124
-
125
- st.session_state.db = db
126
- st.session_state.config = config
127
- st.session_state.logger = logger
128
- st.session_state.question_gen = question_gen
129
- st.session_state.rag = rag
130
- st.session_state.user_manager = user_manager
131
- st.session_state.initialized = True
132
-
133
- except Exception as e:
134
- st.error(f"Error loading initial database: {str(e)}")
135
- return None
136
-
137
- async def process_question(question: str):
138
- """Process a question and update the chat state"""
139
- try:
140
- relevant_docs = st.session_state.db.search(question)
141
- context = st.session_state.rag.create_context(relevant_docs)
142
- answer = await st.session_state.rag.get_answer(
143
- question=question,
144
- context=context,
145
- user_info=st.session_state.user_info
146
- )
147
-
148
- follow_up_questions = await st.session_state.question_gen.generate_questions(
149
- question,
150
- answer,
151
- st.session_state.user_info
152
- )
153
-
154
- st.session_state.chat_memory.add_interaction(question, answer)
155
- st.session_state.logger.log_interaction(
156
- question,
157
- answer,
158
- st.session_state.user_info
159
- )
160
-
161
- st.session_state.message_counter += 1
162
-
163
- st.session_state.messages.append({
164
- "role": "user",
165
- "content": question,
166
- "message_id": st.session_state.message_counter
167
- })
168
-
169
- st.session_state.messages.append({
170
- "role": "assistant",
171
- "content": answer,
172
- "questions": follow_up_questions,
173
- "message_id": st.session_state.message_counter
174
- })
175
-
176
- except Exception as e:
177
- st.error(f"Error processing question: {str(e)}")
178
-
179
- def render_user_form():
180
- """Render the user information form in the sidebar"""
181
- st.sidebar.title(UI_TEXT["sidebar_title"])
182
-
183
- with st.sidebar.form("user_info_form"):
184
- name = st.text_input(UI_TEXT["form_name"])
185
- college = st.text_input(UI_TEXT["form_college"])
186
- degree = st.text_input(UI_TEXT["form_degree"])
187
- year = st.number_input(UI_TEXT["form_year"], min_value=1, max_value=5, step=1)
188
- career_goals = st.text_area(UI_TEXT["form_goals"])
189
- has_internship = st.checkbox(UI_TEXT["form_internship"])
190
- has_placement = st.checkbox(UI_TEXT["form_placement"])
191
-
192
- submitted = st.form_submit_button(UI_TEXT["form_submit"])
193
-
194
- if submitted:
195
- if name and college and degree and year and career_goals:
196
- user_info = UserInfo(
197
- name=name,
198
- college=college,
199
- degree=degree,
200
- year=year,
201
- career_goals=career_goals,
202
- has_internship=has_internship,
203
- has_placement=has_placement
204
- )
205
-
206
- if st.session_state.user_manager.save_user_info(user_info):
207
- st.session_state.user_info = user_info
208
- st.sidebar.success(UI_TEXT["form_success"])
209
- else:
210
- st.sidebar.error(UI_TEXT["form_error"])
211
- else:
212
- st.sidebar.warning(UI_TEXT["form_required"])
213
-
214
- def main():
215
- # Initialize session state
216
- init_session_state()
217
-
218
- # Load initial database and components if not already initialized
219
- if not st.session_state.initialized:
220
- load_initial_database()
221
-
222
- # Render user form in sidebar
223
- render_user_form()
224
-
225
- # Display title
226
- st.title("Career Guidance Chatbot")
227
-
228
- # Welcome message
229
- if not st.session_state.messages:
230
- st.markdown(UI_TEXT["welcome_message"])
231
-
232
- # Display initial questions as buttons
233
- cols = st.columns(2)
234
- for i, question in enumerate(UI_TEXT["initial_questions"]):
235
- if cols[i % 2].button(question, key=f"initial_{i}", use_container_width=True):
236
- asyncio.run(process_question(question))
237
-
238
- # Display chat history
239
- for message in st.session_state.messages:
240
- if message["role"] == "user":
241
- st.markdown(
242
- f'<div class="user-message">πŸ‘€ {message["content"]}</div>',
243
- unsafe_allow_html=True
244
- )
245
- else:
246
- st.markdown(
247
- f'<div class="assistant-message">πŸŽ“ {message["content"]}</div>',
248
- unsafe_allow_html=True
249
- )
250
-
251
- if message.get("questions"):
252
- cols = st.columns(2)
253
- for i, question in enumerate(message["questions"]):
254
- if cols[i % 2].button(
255
- question,
256
- key=f"followup_{message['message_id']}_{i}",
257
- use_container_width=True
258
- ):
259
- asyncio.run(process_question(question))
260
-
261
- # Input area
262
- with st.container():
263
- # Create a form for input
264
- with st.form(key='input_form'):
265
- question = st.text_input(
266
- UI_TEXT["input_label"],
267
- key="user_input",
268
- placeholder=UI_TEXT["input_placeholder"]
269
- )
270
- submit = st.form_submit_button("Send")
271
-
272
- # Process input when submitted
273
- if submit and question:
274
- with st.spinner("πŸ”„ Processing your message..."):
275
- asyncio.run(process_question(question))
276
- if 'processed_questions' not in st.session_state:
277
- st.session_state.processed_questions = set()
278
- st.session_state.processed_questions.add(question)
279
- st.rerun()
280
-
281
- # Clear chat controls
282
- cols = st.columns([4, 1])
283
- if cols[1].button(UI_TEXT["clear_chat"], use_container_width=True):
284
- st.session_state.messages = []
285
- st.session_state.chat_memory.clear_history()
286
- st.session_state.message_counter = 0
287
- if 'processed_questions' in st.session_state:
288
- st.session_state.processed_questions = set()
289
- st.rerun()
290
-
291
- if __name__ == "__main__":
292
  main()
 
1
+ import streamlit as st
2
+ from typing import List, Dict, Any, Optional
3
+ import asyncio
4
+ from back import (ChatConfig, ChatLogger, ChatMemory, QuestionGenerator,
5
+ GeminiRAG, ProductDatabase, UserManager, UserInfo)
6
+ import os
7
+
8
+ # UI Text in English
9
+ UI_TEXT = {
10
+ "welcome_message": """
11
+ Welcome to the Career Guidance Chatbot! πŸŽ“
12
+
13
+ Hi! We are here to help you navigate your career journey.
14
+
15
+ Ask any questions you have about internships, placements, skills development, career paths, or anything else related to your future career.
16
+
17
+ Choose a question below or ask your own.
18
+ """,
19
+ "input_placeholder": "Enter your question here...",
20
+ "input_label": "Ask Anything:",
21
+ "clear_chat": "Clear Chat",
22
+ "sidebar_title": "Tell Us About Yourself for Personalized Guidance",
23
+ "form_name": "Your Name",
24
+ "form_college": "College Name",
25
+ "form_degree": "Degree",
26
+ "form_year": "Year of Study",
27
+ "form_goals": "Your Career Goals",
28
+ "form_internship": "Have you done an internship?",
29
+ "form_placement": "Have you secured a placement?",
30
+ "form_submit": "Get Personalized Advice",
31
+ "form_success": "βœ… Personalized advice activated!",
32
+ "form_error": "❌ Error saving information. Please try again.",
33
+ "form_required": "Please fill in all required fields.",
34
+ "initial_questions": [
35
+ "What are some good career options in my field?",
36
+ "How do I get an internship in my desired field?",
37
+ "What skills are most important for success in this career path?",
38
+ "What are some tips for preparing for job interviews?"
39
+ ]
40
+ }
41
+
42
+ def init_session_state():
43
+ """Initialize all session state variables"""
44
+ defaults = {
45
+ 'initialized': False,
46
+ 'chat_memory': ChatMemory(),
47
+ 'messages': [],
48
+ 'message_counter': 0,
49
+ 'processed_questions': set(),
50
+ 'trigger_rerun': False,
51
+ 'user_info': None,
52
+ 'show_suggestions': False
53
+ }
54
+
55
+ for key, value in defaults.items():
56
+ if key not in st.session_state:
57
+ st.session_state[key] = value
58
+
59
+ # Configure the page
60
+ st.set_page_config(
61
+ page_title="Career Guidance Chatbot",
62
+ page_icon="πŸŽ“",
63
+ layout="wide"
64
+ )
65
+
66
+ # Custom CSS
67
+ st.markdown("""
68
+ <style>
69
+ .user-message {
70
+ background-color: #98BF64;
71
+ color: black;
72
+ padding: 15px;
73
+ border-radius: 15px;
74
+ margin: 10px 0;
75
+ }
76
+ .assistant-message {
77
+ background-color: #F9CB9C;
78
+ color: #F6B26B;
79
+ padding: 15px;
80
+ border-radius: 15px;
81
+ margin: 10px 0;
82
+ }
83
+ .stButton > button {
84
+ background-color: #212B2A;
85
+ color: white;
86
+ border: none;
87
+ padding: 10px 15px;
88
+ border-radius: 5px;
89
+ transition: background-color 0.3s;
90
+ }
91
+ .stButton > button:hover {
92
+ background-color: #45A049;
93
+ }
94
+ </style>
95
+ """, unsafe_allow_html=True)
96
+
97
+ def initialize_components():
98
+ """Initialize and cache application components"""
99
+ try:
100
+ config = ChatConfig()
101
+ logger = ChatLogger(config.log_file)
102
+ question_gen = QuestionGenerator(config.gemini_api_key)
103
+ rag = GeminiRAG(config.gemini_api_key)
104
+ user_manager = UserManager(config.user_data_file)
105
+ return config, logger, question_gen, rag, user_manager
106
+ except Exception as e:
107
+ st.error(f"Error initializing components: {str(e)}")
108
+ raise e
109
+
110
+ def load_initial_database():
111
+ """Load the default database"""
112
+ if not st.session_state.initialized:
113
+ try:
114
+ config, logger, question_gen, rag, user_manager = initialize_components()
115
+
116
+ db = ProductDatabase(config)
117
+ # Here, you would process your markdown files to create the database
118
+ # Replace 'path/to/your/markdown/files' with the actual path
119
+ for filename in os.listdir("blogs"):
120
+ if filename.endswith(".md"):
121
+ with open(os.path.join("blogs", filename), "r", encoding="utf-8") as f:
122
+ markdown_content = f.read()
123
+ db.process_markdown(markdown_content)
124
+
125
+ st.session_state.db = db
126
+ st.session_state.config = config
127
+ st.session_state.logger = logger
128
+ st.session_state.question_gen = question_gen
129
+ st.session_state.rag = rag
130
+ st.session_state.user_manager = user_manager
131
+ st.session_state.initialized = True
132
+
133
+ except Exception as e:
134
+ st.error(f"Error loading initial database: {str(e)}")
135
+ return None
136
+
137
+ async def process_question(question: str):
138
+ """Process a question and update the chat state"""
139
+ try:
140
+ relevant_docs = st.session_state.db.search(question)
141
+ context = st.session_state.rag.create_context(relevant_docs)
142
+ answer = await st.session_state.rag.get_answer(
143
+ question=question,
144
+ context=context,
145
+ user_info=st.session_state.user_info
146
+ )
147
+
148
+ follow_up_questions = await st.session_state.question_gen.generate_questions(
149
+ question,
150
+ answer,
151
+ st.session_state.user_info
152
+ )
153
+
154
+ st.session_state.chat_memory.add_interaction(question, answer)
155
+ st.session_state.logger.log_interaction(
156
+ question,
157
+ answer,
158
+ st.session_state.user_info
159
+ )
160
+
161
+ st.session_state.message_counter += 1
162
+
163
+ st.session_state.messages.append({
164
+ "role": "user",
165
+ "content": question,
166
+ "message_id": st.session_state.message_counter
167
+ })
168
+
169
+ st.session_state.messages.append({
170
+ "role": "assistant",
171
+ "content": answer,
172
+ "questions": follow_up_questions,
173
+ "message_id": st.session_state.message_counter
174
+ })
175
+
176
+ except Exception as e:
177
+ st.error(f"Error processing question: {str(e)}")
178
+
179
+ def render_user_form():
180
+ """Render the user information form in the sidebar"""
181
+ st.sidebar.title(UI_TEXT["sidebar_title"])
182
+
183
+ with st.sidebar.form("user_info_form"):
184
+ name = st.text_input(UI_TEXT["form_name"])
185
+ college = st.text_input(UI_TEXT["form_college"])
186
+ degree = st.text_input(UI_TEXT["form_degree"])
187
+ year = st.number_input(UI_TEXT["form_year"], min_value=1, max_value=5, step=1)
188
+ career_goals = st.text_area(UI_TEXT["form_goals"])
189
+ has_internship = st.checkbox(UI_TEXT["form_internship"])
190
+ has_placement = st.checkbox(UI_TEXT["form_placement"])
191
+
192
+ submitted = st.form_submit_button(UI_TEXT["form_submit"])
193
+
194
+ if submitted:
195
+ if name and college and degree and year and career_goals:
196
+ user_info = UserInfo(
197
+ name=name,
198
+ college=college,
199
+ degree=degree,
200
+ year=year,
201
+ career_goals=career_goals,
202
+ has_internship=has_internship,
203
+ has_placement=has_placement
204
+ )
205
+
206
+ if st.session_state.user_manager.save_user_info(user_info):
207
+ st.session_state.user_info = user_info
208
+ st.sidebar.success(UI_TEXT["form_success"])
209
+ else:
210
+ st.sidebar.error(UI_TEXT["form_error"])
211
+ else:
212
+ st.sidebar.warning(UI_TEXT["form_required"])
213
+
214
+ def main():
215
+ # Initialize session state
216
+ init_session_state()
217
+
218
+ # Load initial database and components if not already initialized
219
+ if not st.session_state.initialized:
220
+ load_initial_database()
221
+
222
+ # Render user form in sidebar
223
+ render_user_form()
224
+
225
+ # Display title
226
+ st.title("Career Guidance Chatbot")
227
+
228
+ # Welcome message
229
+ if not st.session_state.messages:
230
+ st.markdown(UI_TEXT["welcome_message"])
231
+
232
+ # Display initial questions as buttons
233
+ cols = st.columns(2)
234
+ for i, question in enumerate(UI_TEXT["initial_questions"]):
235
+ if cols[i % 2].button(question, key=f"initial_{i}", use_container_width=True):
236
+ asyncio.run(process_question(question))
237
+
238
+ # Display chat history
239
+ for message in st.session_state.messages:
240
+ if message["role"] == "user":
241
+ st.markdown(
242
+ f'<div class="user-message">πŸ‘€ {message["content"]}</div>',
243
+ unsafe_allow_html=True
244
+ )
245
+ else:
246
+ st.markdown(
247
+ f'<div class="assistant-message">πŸŽ“ {message["content"]}</div>',
248
+ unsafe_allow_html=True
249
+ )
250
+
251
+ if message.get("questions"):
252
+ cols = st.columns(2)
253
+ for i, question in enumerate(message["questions"]):
254
+ if cols[i % 2].button(
255
+ question,
256
+ key=f"followup_{message['message_id']}_{i}",
257
+ use_container_width=True
258
+ ):
259
+ asyncio.run(process_question(question))
260
+
261
+ # Input area
262
+ with st.container():
263
+ # Create a form for input
264
+ with st.form(key='input_form'):
265
+ question = st.text_input(
266
+ UI_TEXT["input_label"],
267
+ key="user_input",
268
+ placeholder=UI_TEXT["input_placeholder"]
269
+ )
270
+ submit = st.form_submit_button("Send")
271
+
272
+ # Process input when submitted
273
+ if submit and question:
274
+ with st.spinner("πŸ”„ Processing your message..."):
275
+ asyncio.run(process_question(question))
276
+ if 'processed_questions' not in st.session_state:
277
+ st.session_state.processed_questions = set()
278
+ st.session_state.processed_questions.add(question)
279
+ st.rerun()
280
+
281
+ # Clear chat controls
282
+ cols = st.columns([4, 1])
283
+ if cols[1].button(UI_TEXT["clear_chat"], use_container_width=True):
284
+ st.session_state.messages = []
285
+ st.session_state.chat_memory.clear_history()
286
+ st.session_state.message_counter = 0
287
+ if 'processed_questions' in st.session_state:
288
+ st.session_state.processed_questions = set()
289
+ st.rerun()
290
+
291
+ if __name__ == "__main__":
292
  main()