KatGaw commited on
Commit
37823c4
·
1 Parent(s): 19d2a16

adding files

Browse files
Files changed (1) hide show
  1. app.py +321 -0
app.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain_openai import ChatOpenAI
3
+ from tools import sentiment_analysis_util
4
+ import pandas as pd
5
+ from dotenv import load_dotenv
6
+ import os
7
+ from datetime import datetime
8
+ import json
9
+ from tavily import TavilyClient
10
+
11
+ st.set_page_config(page_title="Personalized Success Recipe Generator", layout="wide")
12
+ st.image('el_pic.png')
13
+ load_dotenv()
14
+ OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
15
+ TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]
16
+
17
+ # Initialize session state
18
+ if "user_profile" not in st.session_state:
19
+ st.session_state["user_profile"] = {}
20
+ if "company_info" not in st.session_state:
21
+ st.session_state["company_info"] = {}
22
+ if "success_recipe" not in st.session_state:
23
+ st.session_state["success_recipe"] = ""
24
+ if "messages" not in st.session_state:
25
+ st.session_state["messages"] = [{"role": "system", "content": "I'm here to help you with your personalized success strategy! Ask me anything about your goals, career, or the success recipe I've created for you."}]
26
+
27
+ # Left Sidebar - User Inputs
28
+ with st.sidebar:
29
+ st.title("📝 Your Profile")
30
+
31
+ name = st.text_input("Full Name", placeholder="Enter your full name")
32
+ gender = st.selectbox("Gender", ["Male", "Female", "Non-binary", "Prefer not to say"])
33
+ career_stage = st.selectbox("Career Stage", ["Young Adult (18-25)", "Mid-Career (26-45)", "Older/Retiree (45+)"])
34
+ job_position = st.text_input("Job Position", placeholder="e.g., Software Engineer, Marketing Manager")
35
+ country_origin = st.text_input("Country of Origin", placeholder="e.g., United States, Japan, Germany")
36
+ company = st.text_input("Company Name", placeholder="e.g., Google, Microsoft, Startup Inc.")
37
+
38
+ # Generate button
39
+ generate_button = st.button("🚀 Generate Success Recipe", type="primary", disabled=not (name and company and job_position and country_origin))
40
+
41
+ if generate_button:
42
+ # Store user profile when generate button is pressed
43
+ st.session_state["user_profile"] = {
44
+ "name": name,
45
+ "gender": gender,
46
+ "career_stage": career_stage,
47
+ "job_position": job_position,
48
+ "country_origin": country_origin,
49
+ "company": company
50
+ }
51
+ # Reset success recipe to trigger regeneration
52
+ st.session_state["success_recipe"] = ""
53
+ st.session_state["company_info"] = {}
54
+ st.rerun()
55
+
56
+ # Main Window
57
+ st.title("🎯 Personalized Success Recipe Generator")
58
+
59
+ # Auto-search company information when user profile exists and company info is needed
60
+ if st.session_state.get("user_profile") and not st.session_state.get("company_info"):
61
+ company = st.session_state["user_profile"]["company"]
62
+ with st.spinner(f"Searching for information about {company}..."):
63
+ try:
64
+ # Initialize Tavily client
65
+ tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
66
+
67
+ # Search for company information
68
+ search_query = f"Latest news and information about {company} company"
69
+ response = tavily_client.search(query=search_query, search_depth="advanced", max_results=10)
70
+
71
+ # Extract and process company information
72
+ company_articles = []
73
+ for result in response.get('results', []):
74
+ article = {
75
+ 'title': result.get('title', ''),
76
+ 'content': result.get('content', ''),
77
+ 'url': result.get('url', ''),
78
+ 'published_date': result.get('published_date', ''),
79
+ 'score': result.get('score', 0)
80
+ }
81
+ company_articles.append(article)
82
+
83
+ # Store company information
84
+ st.session_state["company_info"] = {
85
+ "company_name": company,
86
+ "articles": company_articles,
87
+ "search_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
88
+ }
89
+
90
+ st.success(f"Found {len(company_articles)} articles about {company}!")
91
+
92
+ # Analyze company culture and success
93
+ with st.spinner("Analyzing company culture and success metrics..."):
94
+ try:
95
+ # Prepare company analysis prompt
96
+ company_analysis_prompt = f"""
97
+ Analyze the following company information and provide insights about:
98
+
99
+ 1. **Company Success Level**: Is this company successful, struggling, or growing? What indicators show this?
100
+ 2. **Company Culture Type**: Is this an entrepreneurial/startup culture, mission-driven organization, or bureaucratic/corporate environment?
101
+ 3. **Leadership Structure**: What type of leadership and decision-making structure does this company have?
102
+ 4. **Position Analysis**: For someone in the role of {st.session_state["user_profile"]["job_position"]}, what level of autonomy and influence would they typically have?
103
+ 5. **Growth Opportunities**: What opportunities exist for career advancement and skill development?
104
+ 6. **Challenges**: What challenges might someone face in this company and role?
105
+
106
+ Company Articles:
107
+ {json.dumps(company_articles, indent=2)}
108
+
109
+ Provide a comprehensive analysis that will help create a personalized success strategy.
110
+ """
111
+
112
+ # Initialize ChatOpenAI for company analysis
113
+ analysis_client = ChatOpenAI(
114
+ model="gpt-4o",
115
+ temperature=0.3,
116
+ api_key=OPENAI_API_KEY
117
+ )
118
+
119
+ # Generate company analysis
120
+ analysis_messages = [
121
+ {"role": "system", "content": "You are a business analyst and organizational culture expert who analyzes companies to provide insights about their success, culture, and career opportunities."},
122
+ {"role": "user", "content": company_analysis_prompt}
123
+ ]
124
+
125
+ analysis_response = analysis_client.invoke(analysis_messages)
126
+ company_analysis = analysis_response.content
127
+
128
+ # Store company analysis
129
+ st.session_state["company_info"]["analysis"] = company_analysis
130
+
131
+ st.info("Company analysis completed!")
132
+
133
+ except Exception as e:
134
+ st.error(f"Error analyzing company information: {str(e)}")
135
+ st.session_state["company_info"]["analysis"] = "Company analysis unavailable due to error."
136
+
137
+ except Exception as e:
138
+ st.error(f"Error searching for company information: {str(e)}")
139
+
140
+ # Auto-generate and save profile summary
141
+ if st.session_state.get("user_profile") and st.session_state.get("company_info"):
142
+ profile = st.session_state["user_profile"]
143
+ company_info = st.session_state["company_info"]
144
+
145
+ # Generate markdown content
146
+ markdown_content = f"""# Personal Success Profile
147
+
148
+ ## Personal Information
149
+ - **Name:** {profile['name']}
150
+ - **Gender:** {profile['gender']}
151
+ - **Career Stage:** {profile['career_stage']}
152
+ - **Job Position:** {profile['job_position']}
153
+ - **Country of Origin:** {profile['country_origin']}
154
+
155
+ ## Company Information
156
+ - **Company:** {company_info['company_name']}
157
+ - **Research Date:** {company_info['search_date']}
158
+
159
+ ### Company Analysis
160
+ {company_info.get('analysis', 'Company analysis not available')}
161
+
162
+ ### Recent Company News and Insights
163
+ """
164
+
165
+ for i, article in enumerate(company_info['articles'][:10], 1):
166
+ markdown_content += f"""
167
+ #### Article {i}: {article['title']}
168
+ - **Content:** {article['content'][:300]}...
169
+ - **URL:** {article['url']}
170
+ - **Published:** {article['published_date']}
171
+ - **Relevance Score:** {article['score']:.2f}
172
+
173
+ ---
174
+ """
175
+
176
+ # Auto-save profile summary
177
+ profile_filename = f"profile_{profile['name'].replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
178
+ with open(profile_filename, 'w', encoding='utf-8') as f:
179
+ f.write(markdown_content)
180
+
181
+ st.info(f"Profile summary automatically saved as {profile_filename}")
182
+
183
+ # Auto-generate success recipe
184
+ if st.session_state.get("user_profile") and st.session_state.get("company_info") and not st.session_state.get("success_recipe"):
185
+ with st.spinner("Generating your personalized success recipe..."):
186
+ try:
187
+ # Read the Big Goals book
188
+ with open('big_goals_step_by_step.md', 'r', encoding='utf-8') as f:
189
+ big_goals_content = f.read()
190
+
191
+ # Prepare context for RAG
192
+ profile = st.session_state["user_profile"]
193
+ company_info = st.session_state["company_info"]
194
+
195
+ # Initialize ChatOpenAI
196
+ client = ChatOpenAI(
197
+ model="gpt-4o",
198
+ temperature=0.7,
199
+ api_key=OPENAI_API_KEY
200
+ )
201
+
202
+ # Create prompt for success recipe generation
203
+ prompt = f"""
204
+ Based on the user profile, company information, company analysis, and the Big Goals book content provided, create a detailed, actionable success recipe for {profile['name']}.
205
+
206
+ User Profile:
207
+ - Name: {profile['name']}
208
+ - Gender: {profile['gender']}
209
+ - Career Stage: {profile['career_stage']}
210
+ - Job Position: {profile['job_position']}
211
+ - Country of Origin: {profile['country_origin']}
212
+ - Company: {profile['company']}
213
+
214
+ Company Analysis:
215
+ {company_info.get('analysis', 'Company analysis not available')}
216
+
217
+ The recipe should be highly specific and practical, focusing on HOW to succeed, not just what to do. Include:
218
+
219
+ 1. **Cultural Integration**: How to leverage their {profile['country_origin']} heritage as a professional advantage
220
+ 2. **Career Stage Strategy**: Specific tactics for their {profile['career_stage']} phase
221
+ 3. **Job-Specific Actions**: Concrete steps for their role as {profile['job_position']}
222
+ 4. **Company Alignment**: How to succeed within their specific company culture (use the company analysis insights)
223
+ 5. **Position Autonomy**: Leverage their level of autonomy and influence in their role
224
+ 6. **Big Goals Framework**: Direct application of the book's principles with specific examples
225
+
226
+ Format as a comprehensive success recipe with:
227
+ - **Cultural Reflection**: How their background shapes their approach to work
228
+ - **Vision Statement**: A clear, inspiring vision that incorporates their values
229
+ - **Action Steps**: Specific, measurable actions they can take immediately
230
+ - **Big Goals References**: Direct quotes and chapter references from the book
231
+ - **Cultural Considerations**: How to navigate workplace dynamics with their background
232
+ - **Company-Specific Strategies**: Tactics tailored to their organization's culture and success level
233
+ - **Position-Specific Tactics**: Actions based on their role's autonomy and influence level
234
+ - **Timeline**: When to implement each step
235
+ - **Success Metrics**: How to measure progress
236
+
237
+ Make it deeply personal, culturally aware, and immediately actionable. Focus on the "how" and "why" behind each recommendation. Use the company analysis to inform your recommendations about the work environment and opportunities.
238
+ """
239
+
240
+ # Generate the success recipe
241
+ messages = [
242
+ {"role": "system", "content": "You are an expert career coach and success strategist who creates highly detailed, actionable success recipes. Focus on specific HOW-TO steps, cultural integration strategies, and practical implementation guidance. Always include concrete examples, timelines, and measurable outcomes. Reference specific chapters and quotes from the Big Goals book to support recommendations."},
243
+ {"role": "user", "content": prompt}
244
+ ]
245
+
246
+ response = client.invoke(messages)
247
+ success_recipe = response.content
248
+
249
+ # Store the success recipe
250
+ st.session_state["success_recipe"] = success_recipe
251
+
252
+ # Auto-save the success recipe
253
+ recipe_filename = f"success_recipe_{profile['name'].replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
254
+ with open(recipe_filename, 'w', encoding='utf-8') as f:
255
+ f.write(f"# Success Recipe for {profile['name']}\n\n{success_recipe}")
256
+
257
+ st.success(f"Success recipe automatically saved as {recipe_filename}!")
258
+
259
+ except Exception as e:
260
+ st.error(f"Error generating success recipe: {str(e)}")
261
+
262
+ # Display success recipe in main window
263
+ if st.session_state.get("success_recipe"):
264
+ st.subheader("🎯 Your Personalized Success Recipe")
265
+ st.markdown(st.session_state["success_recipe"])
266
+
267
+ # Download button for success recipe
268
+ st.download_button(
269
+ label="📥 Download Success Recipe",
270
+ data=st.session_state["success_recipe"],
271
+ file_name=f"success_recipe_{st.session_state['user_profile']['name'].replace(' ', '_')}.md",
272
+ mime="text/markdown"
273
+ )
274
+
275
+ # Chat functionality in main window
276
+ st.subheader("💬 Chat with Your Success Coach")
277
+
278
+ # Display chat messages
279
+ for msg in st.session_state.messages:
280
+ st.chat_message(msg["role"]).write(msg["content"])
281
+
282
+ # Chat input
283
+ if prompt := st.chat_input("Ask me anything about your success strategy..."):
284
+ # Add user message to chat history
285
+ st.session_state.messages.append({"role": "user", "content": prompt})
286
+ # Display user message in chat message container
287
+ with st.chat_message("user"):
288
+ st.markdown(prompt)
289
+
290
+ # Generate response using ChatOpenAI
291
+ with st.chat_message("assistant"):
292
+ client = ChatOpenAI(
293
+ model="gpt-4o",
294
+ temperature=0.7,
295
+ api_key=OPENAI_API_KEY
296
+ )
297
+
298
+ # Create context for the chat
299
+ context = ""
300
+ if st.session_state.get("user_profile"):
301
+ profile = st.session_state["user_profile"]
302
+ context += f"User Profile: {profile['name']}, {profile['career_stage']}, {profile['job_position']} at {profile['company']}, from {profile['country_origin']}. "
303
+
304
+ if st.session_state.get("success_recipe"):
305
+ context += f"Success Recipe: {st.session_state['success_recipe'][:1000]}... "
306
+
307
+ # Create messages for chat
308
+ chat_messages = [
309
+ {"role": "system", "content": f"You are a helpful success coach. Context: {context} Answer questions about the user's success strategy, goals, and career development."},
310
+ {"role": "user", "content": prompt}
311
+ ]
312
+
313
+ stream = client.chat.completions.create(
314
+ model="gpt-4o",
315
+ messages=chat_messages,
316
+ stream=True,
317
+ )
318
+ response = st.write_stream(stream)
319
+
320
+ st.session_state.messages.append({"role": "assistant", "content": response})
321
+