Manyue-DataScientist commited on
Commit
4cbe67b
·
verified ·
1 Parent(s): 4f4b439

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +316 -311
app.py CHANGED
@@ -1,190 +1,190 @@
1
- import streamlit as st
2
- import json
3
- from typing import Dict, List, Any
4
- import re
5
-
6
- def format_project_response(project: dict, indent_level: int = 0) -> str:
7
- """Format project details with proper indentation and spacing"""
8
- indent = " " * indent_level
9
-
10
- response = [f"{indent}• {project['name']}"]
11
- response.append(f"{indent} {project['description']}")
12
-
13
- if 'skills_used' in project:
14
- response.append(f"{indent} Technologies: {', '.join(project['skills_used'])}")
15
-
16
- if 'status' in project:
17
- status = project['status']
18
- if 'development' in status.lower() or 'progress' in status.lower():
19
- response.append(f"{indent} Status: {status}")
20
- if 'confidentiality_note' in project:
21
- response.append(f"{indent} Note: {project['confidentiality_note']}")
22
-
23
- return '\n'.join(response) + '\n'
24
 
25
- def format_skills_response(skills: dict) -> str:
26
- """Format skills with proper hierarchy and spacing"""
27
- response = ["My Technical Expertise:\n"]
28
-
29
- categories = {
30
- 'Machine Learning & AI': ['core', 'frameworks', 'focus_areas'],
31
- 'Programming': ['primary', 'libraries', 'tools'],
32
- 'Data & Analytics': ['databases', 'visualization', 'processing']
33
- }
34
-
35
- for category, subcategories in categories.items():
36
- response.append(f"• {category}")
37
- for subcat in subcategories:
38
- if subcat in skills['machine_learning']:
39
- items = skills['machine_learning'][subcat]
40
- response.append(f" - {subcat.title()}: {', '.join(items)}")
41
- response.append("") # Add spacing between categories
42
-
43
- return '\n'.join(response)
44
-
45
- def analyze_job_description(text: str, knowledge_base: dict) -> str:
46
- """Analyze job description and provide detailed alignment"""
47
- # Extract key requirements
48
- requirements = {
49
- 'technical_tools': set(),
50
- 'soft_skills': set(),
51
- 'responsibilities': set()
52
- }
53
-
54
- # Common technical tools and skills
55
- tech_keywords = {
56
- 'data science', 'analytics', 'visualization', 'tableau', 'python',
57
- 'machine learning', 'modeling', 'automation', 'sql', 'data analysis'
58
- }
59
-
60
- # Common soft skills
61
- soft_keywords = {
62
- 'collaborate', 'communicate', 'analyze', 'design', 'implement',
63
- 'produce insights', 'improve', 'support'
64
- }
65
-
66
- text_lower = text.lower()
67
-
68
- # Extract company name if present
69
- companies = ['rbc', 'shopify', 'google', 'microsoft', 'amazon']
70
- company_name = next((company.upper() for company in companies if company in text_lower), None)
71
-
72
- # Extract requirements
73
- for word in tech_keywords:
74
- if word in text_lower:
75
- requirements['technical_tools'].add(word)
76
-
77
- for word in soft_keywords:
78
- if word in text_lower:
79
- requirements['soft_skills'].add(word)
80
-
81
- # Build response
82
- response_parts = []
83
-
84
- # Company-specific introduction if applicable
85
- if company_name:
86
- response_parts.append(f"Here's how I align with {company_name}'s requirements:\n")
87
- else:
88
- response_parts.append("Based on the job requirements, here's how I align:\n")
89
-
90
- # Technical Skills Alignment
91
- response_parts.append("• Technical Skills Match:")
92
- my_relevant_skills = []
93
- if 'visualization' in requirements['technical_tools'] or 'tableau' in requirements['technical_tools']:
94
- my_relevant_skills.append(" - Proficient in Tableau and data visualization (used in multiple projects)")
95
- if 'data analysis' in requirements['technical_tools']:
96
- my_relevant_skills.append(" - Strong data analysis skills demonstrated in projects like LoanTap Credit Assessment")
97
- if 'machine learning' in requirements['technical_tools'] or 'modeling' in requirements['technical_tools']:
98
- my_relevant_skills.append(" - Experienced in building ML models from scratch (demonstrated in algorithm practice projects)")
99
-
100
- response_parts.extend(my_relevant_skills)
101
- response_parts.append("")
102
-
103
- # Business Understanding
104
- response_parts.append("• Business Acumen:")
105
- response_parts.append(" - Commerce background provides strong understanding of business requirements")
106
- response_parts.append(" - Experience in translating business needs into technical solutions")
107
- response_parts.append(" - Proven ability to communicate technical findings to business stakeholders")
108
- response_parts.append("")
109
-
110
- # Project Experience
111
- response_parts.append("• Relevant Project Experience:")
112
- relevant_projects = []
113
- if 'automation' in requirements['technical_tools']:
114
- relevant_projects.append(" - Developed AI-powered POS system with automated operations")
115
- if 'data analysis' in requirements['technical_tools']:
116
- relevant_projects.append(" - Built credit assessment model for LoanTap using comprehensive data analysis")
117
- if 'machine learning' in requirements['technical_tools']:
118
- relevant_projects.append(" - Created multiple ML models from scratch, including predictive analytics for Ola")
119
-
120
- response_parts.extend(relevant_projects)
121
- response_parts.append("")
122
-
123
- # Education and Additional Qualifications
124
- response_parts.append("• Additional Strengths:")
125
- response_parts.append(" - Currently pursuing advanced AI/ML education in Canada")
126
- response_parts.append(" - Strong foundation in both technical implementation and business analysis")
127
- response_parts.append(" - Experience in end-to-end project delivery and deployment")
128
-
129
- return '\n'.join(response_parts)
130
 
131
- def format_story_response(knowledge_base: dict) -> str:
132
- """Format background story with proper structure"""
133
- response_parts = ["My Journey from Commerce to ML/AI:\n"]
134
-
135
- # Education Background
136
- response_parts.append("• Education Background:")
137
- response_parts.append(f" - Commerce degree from {knowledge_base['education']['undergraduate']['institution']}")
138
- response_parts.append(f" - Currently at {knowledge_base['education']['postgraduate'][0]['institution']}")
139
- response_parts.append(f" - Also enrolled at {knowledge_base['education']['postgraduate'][1]['institution']}")
140
- response_parts.append("")
141
-
142
- # Career Transition
143
- response_parts.append("• Career Transition:")
144
- transition = next((qa['answer'] for qa in knowledge_base['frequently_asked_questions']
145
- if 'transition' in qa['question'].lower()), '')
146
- response_parts.append(f" - {transition[:200]}...")
147
- response_parts.append("")
148
-
149
- # Current Focus
150
- response_parts.append("• Current Focus:")
151
- response_parts.append(" - Building practical ML projects")
152
- response_parts.append(" - Advancing AI/ML education in Canada")
153
- response_parts.append("")
154
-
155
- # Goals
156
- response_parts.append("• Future Goals:")
157
- response_parts.append(" - Secure ML Engineering role in Canada")
158
- response_parts.append(" - Develop innovative AI solutions")
159
- response_parts.append(" - Contribute to cutting-edge ML projects")
160
-
161
- return '\n'.join(response_parts)
162
-
163
- def format_standout_response() -> str:
164
- """Format response about standout qualities"""
165
- response_parts = ["What Makes Me Stand Out:\n"]
166
- response_parts.append("• Unique Background:")
167
- response_parts.append(" - Successfully transitioned from commerce to tech")
168
- response_parts.append(" - Blend of business acumen and technical expertise")
169
- response_parts.append("")
170
-
171
- response_parts.append("• Practical Experience:")
172
- response_parts.append(" - Built multiple ML projects from scratch")
173
- response_parts.append(" - Focus on real-world applications")
174
- response_parts.append("")
175
-
176
- response_parts.append("• Technical Depth:")
177
- response_parts.append(" - Strong foundation in ML/AI principles")
178
- response_parts.append(" - Experience with end-to-end project implementation")
179
- response_parts.append("")
180
-
181
- response_parts.append("• Innovation Focus:")
182
- response_parts.append(" - Developing novel solutions in ML/AI")
183
- response_parts.append(" - Emphasis on practical impact")
184
-
185
- return '\n'.join(response_parts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
- def add_relevant_links(response: str, query: str, knowledge_base: dict) -> str:
188
  """Add relevant links based on query context"""
189
  query_lower = query.lower()
190
  links = []
@@ -205,133 +205,138 @@
205
 
206
  return response
207
 
208
- def handle_market_conditions(knowledge_base: dict) -> str:
209
- """Handle market condition related queries with perspective"""
210
- market_outlook = knowledge_base['personal_details']['perspectives']['market_outlook']
211
-
212
- # Enhanced formatting for better readability
213
- response_parts = [
214
- "Here's my perspective on the current market situation:\n",
215
- f"• {market_outlook['job_market']}",
216
- f"\n• {market_outlook['value_proposition']}",
217
- f"\n• {market_outlook['strategy']}"
218
- ]
219
-
220
- return '\n'.join(response_parts)
221
 
222
- def handle_general_query(query: str, knowledge_base: dict) -> str:
223
- """Enhanced handling of general queries"""
224
- query_lower = query.lower()
225
-
226
- # Improved weather-related query detection
227
- if any(word in query_lower for word in ['weather', 'temperature', 'climate', 'cold', 'hot', 'warm']):
228
- return knowledge_base['personal_details']['common_queries']['weather']
229
-
230
- # Enhanced market-related query detection
231
- if any(phrase in query_lower for word in ['market', 'job market', 'jobs', 'opportunities', 'hiring']):
232
- return handle_market_conditions(knowledge_base)
233
-
234
- # More specific job fit query detection
235
- if any(phrase in query_lower for phrase in ['job description', 'job posting', 'job requirement', 'good fit']):
236
- return ("Please paste the job description you'd like me to analyze. I'll evaluate how my skills and experience align with the requirements.")
237
-
238
- # Default to personal summary
239
- return knowledge_base['personal_details']['professional_summary']
240
 
241
- def generate_response(query: str, knowledge_base: dict) -> str:
242
- """Enhanced response generation with improved pattern matching"""
243
- query_lower = query.lower()
244
-
245
- # Enhanced market conditions detection
246
- if any(word in query_lower for word in ['market', 'job market', 'hiring']) or \
247
- any(phrase in query_lower for phrase in ['market down', 'market conditions', 'current situation']):
248
- return handle_market_conditions(knowledge_base)
249
-
250
- # Enhanced job description analysis detection
251
- if ('job description' in query_lower or 'job posting' in query_lower) or \
252
- (len(query.split()) > 20 and any(word in query_lower for word in
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  ['requirements', 'qualifications', 'looking for', 'responsibilities', 'skills needed'])):
254
- if len(query.split()) < 20:
255
- return "Please paste the complete job description, and I'll analyze how well I match the requirements."
256
- return analyze_job_description(query, knowledge_base)
257
-
258
- # Enhanced weather query detection
259
- if any(word in query_lower for word in ['weather', 'temperature', 'climate', 'cold', 'hot', 'warm']):
260
- return handle_general_query(query, knowledge_base)
261
-
262
- # Existing handlers remain unchanged
263
- if any(word in query_lower for word in ['list', 'project', 'portfolio', 'built', 'created', 'developed']):
264
- response_parts = ["Here are my key projects:\n"]
265
- response_parts.append("Major Projects (In Development):")
266
- for project in knowledge_base['projects']['major_projects']:
267
- response_parts.append(format_project_response(project, indent_level=1))
268
- response_parts.append("Completed Algorithm Implementation Projects:")
269
- for project in knowledge_base['projects']['algorithm_practice_projects']:
270
- response_parts.append(format_project_response(project, indent_level=1))
271
- response = '\n'.join(response_parts)
272
- return add_relevant_links(response, query, knowledge_base)
273
-
274
- elif any(word in query_lower for word in ['background', 'journey', 'story', 'transition']):
275
- return format_story_response(knowledge_base)
276
-
277
- elif any(word in query_lower for word in ['skill', 'know', 'technology', 'stack']):
278
- return format_skills_response(knowledge_base['skills']['technical_skills'])
279
-
280
- elif any(word in query_lower for word in ['stand out', 'unique', 'different', 'special']):
281
- return format_standout_response()
282
-
283
- # General query handler for shorter queries
284
- elif len(query.split()) < 5:
285
- return handle_general_query(query, knowledge_base)
286
-
287
- # Default response
288
- return (f"I'm {knowledge_base['personal_details']['professional_summary']}\n\n"
289
- "You can ask me about:\n"
290
- "• My projects and portfolio\n"
291
- "• My journey from commerce to ML/AI\n"
292
- "• My technical skills and experience\n"
293
- "• My fit for ML/AI roles\n"
294
- "Or paste a job description to see how my profile matches!")
295
-
296
- def main():
297
- st.title("💬 Chat with Manyue's Portfolio")
298
-
299
- # Initialize session state
300
- if "messages" not in st.session_state:
301
- st.session_state.messages = []
302
- if "knowledge_base" not in st.session_state:
303
- try:
304
- with open('knowledge_base.json', 'r', encoding='utf-8') as f:
305
- st.session_state.knowledge_base = json.load(f)
306
- except FileNotFoundError:
307
- st.error("Knowledge base file not found.")
308
- return
309
-
310
- # Display welcome message
311
- if "displayed_welcome" not in st.session_state:
312
- st.write("""
313
- Hi! I'm Manyue's AI assistant. I can tell you about:
314
- - My journey from commerce to ML/AI
315
- - My technical skills and projects
316
- - My fit for ML/AI roles
317
- - You can also paste job descriptions to see how my profile matches!
318
- """)
319
- st.session_state.displayed_welcome = True
320
-
321
- # Create two columns with adjusted ratios
322
- col1, col2 = st.columns([4, 1])
323
-
324
- with col1:
325
- # Display chat messages
326
- for message in st.session_state.messages:
327
- with st.chat_message(message["role"]):
328
- st.markdown(message["content"])
329
-
330
- # Chat input
331
- if prompt := st.chat_input("Ask me anything or paste a job description..."):
332
  # Add user message
333
  st.session_state.messages.append({"role": "user", "content": prompt})
334
-
335
  try:
336
  # Generate and display response
337
  with st.chat_message("assistant"):
@@ -340,9 +345,9 @@
340
  st.session_state.messages.append({"role": "assistant", "content": response})
341
  except Exception as e:
342
  st.error(f"An error occurred: {str(e)}")
343
-
344
  st.rerun()
345
-
346
  with col2:
347
  st.markdown("### Quick Questions")
348
  example_questions = [
@@ -352,7 +357,7 @@
352
  "What's your journey into ML?",
353
  "Paste a job description to see how I match!"
354
  ]
355
-
356
  for question in example_questions:
357
  if st.button(question, key=f"btn_{question}", use_container_width=True):
358
  st.session_state.messages.append({"role": "user", "content": question})
@@ -362,11 +367,11 @@
362
  except Exception as e:
363
  st.error(f"An error occurred: {str(e)}")
364
  st.rerun()
365
-
366
  st.markdown("---")
367
  if st.button("Clear Chat", use_container_width=True):
368
  st.session_state.messages = []
369
  st.rerun()
370
 
371
  if __name__ == "__main__":
372
- main()
 
1
+ import streamlit as st
2
+ import json
3
+ from typing import Dict, List, Any
4
+ import re
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ def format_project_response(project: dict, indent_level: int = 0) -> str:
7
+ """Format project details with proper indentation and spacing"""
8
+ indent = " " * indent_level
9
+
10
+ response = [f"{indent}• {project['name']}"]
11
+ response.append(f"{indent} {project['description']}")
12
+
13
+ if 'skills_used' in project:
14
+ response.append(f"{indent} Technologies: {', '.join(project['skills_used'])}")
15
+
16
+ if 'status' in project:
17
+ status = project['status']
18
+ if 'development' in status.lower() or 'progress' in status.lower():
19
+ response.append(f"{indent} Status: {status}")
20
+ if 'confidentiality_note' in project:
21
+ response.append(f"{indent} Note: {project['confidentiality_note']}")
22
+
23
+ return '\n'.join(response) + '\n'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ def format_skills_response(skills: dict) -> str:
26
+ """Format skills with proper hierarchy and spacing"""
27
+ response = ["My Technical Expertise:\n"]
28
+
29
+ categories = {
30
+ 'Machine Learning & AI': ['core', 'frameworks', 'focus_areas'],
31
+ 'Programming': ['primary', 'libraries', 'tools'],
32
+ 'Data & Analytics': ['databases', 'visualization', 'processing']
33
+ }
34
+
35
+ for category, subcategories in categories.items():
36
+ response.append(f"• {category}")
37
+ for subcat in subcategories:
38
+ if subcat in skills['machine_learning']:
39
+ items = skills['machine_learning'][subcat]
40
+ response.append(f" - {subcat.title()}: {', '.join(items)}")
41
+ response.append("") # Add spacing between categories
42
+
43
+ return '\n'.join(response)
44
+
45
+ def analyze_job_description(text: str, knowledge_base: dict) -> str:
46
+ """Analyze job description and provide detailed alignment"""
47
+ # Extract key requirements
48
+ requirements = {
49
+ 'technical_tools': set(),
50
+ 'soft_skills': set(),
51
+ 'responsibilities': set()
52
+ }
53
+
54
+ # Common technical tools and skills
55
+ tech_keywords = {
56
+ 'data science', 'analytics', 'visualization', 'tableau', 'python',
57
+ 'machine learning', 'modeling', 'automation', 'sql', 'data analysis'
58
+ }
59
+
60
+ # Common soft skills
61
+ soft_keywords = {
62
+ 'collaborate', 'communicate', 'analyze', 'design', 'implement',
63
+ 'produce insights', 'improve', 'support'
64
+ }
65
+
66
+ text_lower = text.lower()
67
+
68
+ # Extract company name if present
69
+ companies = ['rbc', 'shopify', 'google', 'microsoft', 'amazon']
70
+ company_name = next((company.upper() for company in companies if company in text_lower), None)
71
+
72
+ # Extract requirements
73
+ for word in tech_keywords:
74
+ if word in text_lower:
75
+ requirements['technical_tools'].add(word)
76
+
77
+ for word in soft_keywords:
78
+ if word in text_lower:
79
+ requirements['soft_skills'].add(word)
80
+
81
+ # Build response
82
+ response_parts = []
83
+
84
+ # Company-specific introduction if applicable
85
+ if company_name:
86
+ response_parts.append(f"Here's how I align with {company_name}'s requirements:\n")
87
+ else:
88
+ response_parts.append("Based on the job requirements, here's how I align:\n")
89
+
90
+ # Technical Skills Alignment
91
+ response_parts.append("• Technical Skills Match:")
92
+ my_relevant_skills = []
93
+ if 'visualization' in requirements['technical_tools'] or 'tableau' in requirements['technical_tools']:
94
+ my_relevant_skills.append(" - Proficient in Tableau and data visualization (used in multiple projects)")
95
+ if 'data analysis' in requirements['technical_tools']:
96
+ my_relevant_skills.append(" - Strong data analysis skills demonstrated in projects like LoanTap Credit Assessment")
97
+ if 'machine learning' in requirements['technical_tools'] or 'modeling' in requirements['technical_tools']:
98
+ my_relevant_skills.append(" - Experienced in building ML models from scratch (demonstrated in algorithm practice projects)")
99
+
100
+ response_parts.extend(my_relevant_skills)
101
+ response_parts.append("")
102
+
103
+ # Business Understanding
104
+ response_parts.append("• Business Acumen:")
105
+ response_parts.append(" - Commerce background provides strong understanding of business requirements")
106
+ response_parts.append(" - Experience in translating business needs into technical solutions")
107
+ response_parts.append(" - Proven ability to communicate technical findings to business stakeholders")
108
+ response_parts.append("")
109
+
110
+ # Project Experience
111
+ response_parts.append("• Relevant Project Experience:")
112
+ relevant_projects = []
113
+ if 'automation' in requirements['technical_tools']:
114
+ relevant_projects.append(" - Developed AI-powered POS system with automated operations")
115
+ if 'data analysis' in requirements['technical_tools']:
116
+ relevant_projects.append(" - Built credit assessment model for LoanTap using comprehensive data analysis")
117
+ if 'machine learning' in requirements['technical_tools']:
118
+ relevant_projects.append(" - Created multiple ML models from scratch, including predictive analytics for Ola")
119
+
120
+ response_parts.extend(relevant_projects)
121
+ response_parts.append("")
122
+
123
+ # Education and Additional Qualifications
124
+ response_parts.append("• Additional Strengths:")
125
+ response_parts.append(" - Currently pursuing advanced AI/ML education in Canada")
126
+ response_parts.append(" - Strong foundation in both technical implementation and business analysis")
127
+ response_parts.append(" - Experience in end-to-end project delivery and deployment")
128
+
129
+ return '\n'.join(response_parts)
130
+
131
+ def format_story_response(knowledge_base: dict) -> str:
132
+ """Format background story with proper structure"""
133
+ response_parts = ["My Journey from Commerce to ML/AI:\n"]
134
+
135
+ # Education Background
136
+ response_parts.append("• Education Background:")
137
+ response_parts.append(f" - Commerce degree from {knowledge_base['education']['undergraduate']['institution']}")
138
+ response_parts.append(f" - Currently at {knowledge_base['education']['postgraduate'][0]['institution']}")
139
+ response_parts.append(f" - Also enrolled at {knowledge_base['education']['postgraduate'][1]['institution']}")
140
+ response_parts.append("")
141
+
142
+ # Career Transition
143
+ response_parts.append("• Career Transition:")
144
+ transition = next((qa['answer'] for qa in knowledge_base['frequently_asked_questions']
145
+ if 'transition' in qa['question'].lower()), '')
146
+ response_parts.append(f" - {transition[:200]}...")
147
+ response_parts.append("")
148
+
149
+ # Current Focus
150
+ response_parts.append("• Current Focus:")
151
+ response_parts.append(" - Building practical ML projects")
152
+ response_parts.append(" - Advancing AI/ML education in Canada")
153
+ response_parts.append("")
154
+
155
+ # Goals
156
+ response_parts.append("• Future Goals:")
157
+ response_parts.append(" - Secure ML Engineering role in Canada")
158
+ response_parts.append(" - Develop innovative AI solutions")
159
+ response_parts.append(" - Contribute to cutting-edge ML projects")
160
+
161
+ return '\n'.join(response_parts)
162
+
163
+ def format_standout_response() -> str:
164
+ """Format response about standout qualities"""
165
+ response_parts = ["What Makes Me Stand Out:\n"]
166
+ response_parts.append("• Unique Background:")
167
+ response_parts.append(" - Successfully transitioned from commerce to tech")
168
+ response_parts.append(" - Blend of business acumen and technical expertise")
169
+ response_parts.append("")
170
+
171
+ response_parts.append("• Practical Experience:")
172
+ response_parts.append(" - Built multiple ML projects from scratch")
173
+ response_parts.append(" - Focus on real-world applications")
174
+ response_parts.append("")
175
+
176
+ response_parts.append("• Technical Depth:")
177
+ response_parts.append(" - Strong foundation in ML/AI principles")
178
+ response_parts.append(" - Experience with end-to-end project implementation")
179
+ response_parts.append("")
180
+
181
+ response_parts.append("• Innovation Focus:")
182
+ response_parts.append(" - Developing novel solutions in ML/AI")
183
+ response_parts.append(" - Emphasis on practical impact")
184
+
185
+ return '\n'.join(response_parts)
186
 
187
+ def add_relevant_links(response: str, query: str, knowledge_base: dict) -> str:
188
  """Add relevant links based on query context"""
189
  query_lower = query.lower()
190
  links = []
 
205
 
206
  return response
207
 
208
+ import streamlit as st
209
+ import json
210
+ from typing import Dict, List, Any
211
+ import re
 
 
 
 
 
 
 
 
 
212
 
213
+ def handle_market_conditions(knowledge_base: dict) -> str:
214
+ """Handle market condition related queries with perspective"""
215
+ market_outlook = knowledge_base['personal_details']['perspectives']['market_outlook']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
+ # Enhanced formatting for better readability
218
+ response_parts = [
219
+ "Here's my perspective on the current market situation:\n",
220
+ f"• {market_outlook['job_market']}",
221
+ f"\n• {market_outlook['value_proposition']}",
222
+ f"\n• {market_outlook['strategy']}"
223
+ ]
224
+
225
+ return '\n'.join(response_parts)
226
+
227
+ def handle_general_query(query: str, knowledge_base: dict) -> str:
228
+ """Enhanced handling of general queries"""
229
+ query_lower = query.lower()
230
+
231
+ # Improved weather-related query detection
232
+ if any(word in query_lower for word in ['weather', 'temperature', 'climate', 'cold', 'hot', 'warm']):
233
+ return knowledge_base['personal_details']['common_queries']['weather']
234
+
235
+ # Enhanced market-related query detection
236
+ if any(phrase in query_lower for phrase in ['market', 'job market', 'jobs', 'opportunities', 'hiring']):
237
+ return handle_market_conditions(knowledge_base)
238
+
239
+ # More specific job fit query detection
240
+ if any(phrase in query_lower for phrase in ['job description', 'job posting', 'job requirement', 'good fit']):
241
+ return ("Please paste the job description you'd like me to analyze. I'll evaluate how my skills and experience align with the requirements.")
242
+
243
+ # Default to personal summary
244
+ return knowledge_base['personal_details']['professional_summary']
245
+
246
+ def generate_response(query: str, knowledge_base: dict) -> str:
247
+ """Enhanced response generation with improved pattern matching"""
248
+ query_lower = query.lower()
249
+
250
+ # Enhanced market conditions detection
251
+ if any(word in query_lower for word in ['market', 'job market', 'hiring']) or \
252
+ any(phrase in query_lower for phrase in ['market down', 'market conditions', 'current situation']):
253
+ return handle_market_conditions(knowledge_base)
254
+
255
+ # Enhanced job description analysis detection
256
+ if ('job description' in query_lower or 'job posting' in query_lower) or \
257
+ (len(query.split()) > 20 and any(word in query_lower for word in
258
  ['requirements', 'qualifications', 'looking for', 'responsibilities', 'skills needed'])):
259
+ if len(query.split()) < 20:
260
+ return "Please paste the complete job description, and I'll analyze how well I match the requirements."
261
+ return analyze_job_description(query, knowledge_base)
262
+
263
+ # Enhanced weather query detection
264
+ if any(word in query_lower for word in ['weather', 'temperature', 'climate', 'cold', 'hot', 'warm']):
265
+ return handle_general_query(query, knowledge_base)
266
+
267
+ # Existing handlers remain unchanged
268
+ if any(word in query_lower for word in ['list', 'project', 'portfolio', 'built', 'created', 'developed']):
269
+ response_parts = ["Here are my key projects:\n"]
270
+ response_parts.append("Major Projects (In Development):")
271
+ for project in knowledge_base['projects']['major_projects']:
272
+ response_parts.append(format_project_response(project, indent_level=1))
273
+ response_parts.append("Completed Algorithm Implementation Projects:")
274
+ for project in knowledge_base['projects']['algorithm_practice_projects']:
275
+ response_parts.append(format_project_response(project, indent_level=1))
276
+ response = '\n'.join(response_parts)
277
+ return add_relevant_links(response, query, knowledge_base)
278
+
279
+ elif any(word in query_lower for word in ['background', 'journey', 'story', 'transition']):
280
+ return format_story_response(knowledge_base)
281
+
282
+ elif any(word in query_lower for word in ['skill', 'know', 'technology', 'stack']):
283
+ return format_skills_response(knowledge_base['skills']['technical_skills'])
284
+
285
+ elif any(word in query_lower for word in ['stand out', 'unique', 'different', 'special']):
286
+ return format_standout_response()
287
+
288
+ # General query handler for shorter queries
289
+ elif len(query.split()) < 5:
290
+ return handle_general_query(query, knowledge_base)
291
+
292
+ # Default response
293
+ return (f"I'm {knowledge_base['personal_details']['professional_summary']}\n\n"
294
+ "You can ask me about:\n"
295
+ "• My projects and portfolio\n"
296
+ "• My journey from commerce to ML/AI\n"
297
+ "• My technical skills and experience\n"
298
+ "• My fit for ML/AI roles\n"
299
+ "Or paste a job description to see how my profile matches!")
300
+
301
+ def main():
302
+ st.title("💬 Chat with Manyue's Portfolio")
303
+
304
+ # Initialize session state
305
+ if "messages" not in st.session_state:
306
+ st.session_state.messages = []
307
+ if "knowledge_base" not in st.session_state:
308
+ try:
309
+ with open('knowledge_base.json', 'r', encoding='utf-8') as f:
310
+ st.session_state.knowledge_base = json.load(f)
311
+ except FileNotFoundError:
312
+ st.error("Knowledge base file not found.")
313
+ return
314
+
315
+ # Display welcome message
316
+ if "displayed_welcome" not in st.session_state:
317
+ st.write("""
318
+ Hi! I'm Manyue's AI assistant. I can tell you about:
319
+ - My journey from commerce to ML/AI
320
+ - My technical skills and projects
321
+ - My fit for ML/AI roles
322
+ - You can also paste job descriptions to see how my profile matches!
323
+ """)
324
+ st.session_state.displayed_welcome = True
325
+
326
+ # Create two columns with adjusted ratios
327
+ col1, col2 = st.columns([4, 1])
328
+
329
+ with col1:
330
+ # Display chat messages
331
+ for message in st.session_state.messages:
332
+ with st.chat_message(message["role"]):
333
+ st.markdown(message["content"])
334
+
335
+ # Chat input
336
+ if prompt := st.chat_input("Ask me anything or paste a job description..."):
337
  # Add user message
338
  st.session_state.messages.append({"role": "user", "content": prompt})
339
+
340
  try:
341
  # Generate and display response
342
  with st.chat_message("assistant"):
 
345
  st.session_state.messages.append({"role": "assistant", "content": response})
346
  except Exception as e:
347
  st.error(f"An error occurred: {str(e)}")
348
+
349
  st.rerun()
350
+
351
  with col2:
352
  st.markdown("### Quick Questions")
353
  example_questions = [
 
357
  "What's your journey into ML?",
358
  "Paste a job description to see how I match!"
359
  ]
360
+
361
  for question in example_questions:
362
  if st.button(question, key=f"btn_{question}", use_container_width=True):
363
  st.session_state.messages.append({"role": "user", "content": question})
 
367
  except Exception as e:
368
  st.error(f"An error occurred: {str(e)}")
369
  st.rerun()
370
+
371
  st.markdown("---")
372
  if st.button("Clear Chat", use_container_width=True):
373
  st.session_state.messages = []
374
  st.rerun()
375
 
376
  if __name__ == "__main__":
377
+ main()