File size: 54,705 Bytes
d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe 1eb3ba2 d61ddbe |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 |
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import random
import json
import os
import time
import requests
from typing import List, Dict, Any, Optional
import logging
from dotenv import load_dotenv
import pytz
import uuid
import re
import base64
from io import BytesIO
from PIL import Image
# Import the updated Google GenAI SDK
from google import genai
from google.genai import types
# Load environment variables
load_dotenv()
# Set up logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Configure API keys
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "your-api-key")
SERPER_API_KEY = os.getenv("SERPER_API_KEY", "your-serper-api-key")
# Configure Google GenAI
genai.configure(api_key=GOOGLE_API_KEY)
# Init the client
client = genai.Client()
# Model configuration - using Gemini latest model
MODEL_ID = "gemini-2.0-flash-001"
# Constants for global app
EMOTIONS = ["Unmotivated", "Anxious", "Confused", "Excited", "Overwhelmed", "Discouraged"]
GOAL_TYPES = ["Get a job at a big company", "Find an internship", "Change careers", "Improve skills", "Network better"]
USER_DB_PATH = "user_database.json"
RESUME_FOLDER = "user_resumes"
PORTFOLIO_FOLDER = "user_portfolios"
# Ensure folders exist
os.makedirs(RESUME_FOLDER, exist_ok=True)
os.makedirs(PORTFOLIO_FOLDER, exist_ok=True)
# Function declarations for tools
get_job_opportunities = types.FunctionDeclaration(
name="get_job_opportunities",
description="Get relevant job opportunities based on location and career goals",
parameters={
"type": "OBJECT",
"properties": {
"location": {
"type": "STRING",
"description": "The city or country where the user is located",
},
"career_goal": {
"type": "STRING",
"description": "The user's career goal or job interest",
},
"max_results": {
"type": "NUMBER",
"description": "Maximum number of job opportunities to return",
},
},
"required": ["location", "career_goal"],
},
)
generate_document = types.FunctionDeclaration(
name="generate_document_template",
description="Generate a document template for job applications",
parameters={
"type": "OBJECT",
"properties": {
"document_type": {
"type": "STRING",
"description": "Type of document to generate (Resume, Cover Letter, Self-introduction)",
},
"career_field": {
"type": "STRING",
"description": "The career field or industry the document is for",
},
"experience_level": {
"type": "STRING",
"description": "User's experience level (Entry, Mid, Senior)",
},
},
"required": ["document_type"],
},
)
create_routine = types.FunctionDeclaration(
name="create_personalized_routine",
description="Create a personalized career development routine",
parameters={
"type": "OBJECT",
"properties": {
"emotion": {
"type": "STRING",
"description": "User's current emotional state",
},
"goal": {
"type": "STRING",
"description": "User's career goal",
},
"available_time_minutes": {
"type": "NUMBER",
"description": "Available time in minutes per day",
},
"routine_length_days": {
"type": "NUMBER",
"description": "Length of routine in days",
},
},
"required": ["emotion", "goal"],
},
)
analyze_resume = types.FunctionDeclaration(
name="analyze_resume",
description="Analyze a user's resume and provide feedback",
parameters={
"type": "OBJECT",
"properties": {
"resume_text": {
"type": "STRING",
"description": "The full text of the user's resume",
},
"career_goal": {
"type": "STRING",
"description": "The user's career goal or job interest",
},
},
"required": ["resume_text"],
},
)
analyze_portfolio = types.FunctionDeclaration(
name="analyze_portfolio",
description="Analyze a user's portfolio and provide feedback",
parameters={
"type": "OBJECT",
"properties": {
"portfolio_url": {
"type": "STRING",
"description": "URL to the user's portfolio",
},
"portfolio_description": {
"type": "STRING",
"description": "Description of the portfolio content",
},
"career_goal": {
"type": "STRING",
"description": "The user's career goal or job interest",
},
},
"required": ["portfolio_description"],
},
)
# Combine tools
job_tool = types.Tool(function_declarations=[get_job_opportunities])
document_tool = types.Tool(function_declarations=[generate_document])
routine_tool = types.Tool(function_declarations=[create_routine])
resume_tool = types.Tool(function_declarations=[analyze_resume])
portfolio_tool = types.Tool(function_declarations=[analyze_portfolio])
# User database functions
def load_user_database():
"""Load user database from JSON file or create if it doesn't exist"""
try:
with open(USER_DB_PATH, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
# Initialize empty database
db = {'users': {}}
save_user_database(db)
return db
def save_user_database(db):
"""Save user database to JSON file"""
with open(USER_DB_PATH, 'w') as file:
json.dump(db, file, indent=4)
def get_user_profile(user_id):
"""Get user profile from database or create new one"""
db = load_user_database()
if user_id not in db['users']:
db['users'][user_id] = {
"user_id": user_id,
"name": "",
"location": "",
"current_emotion": "",
"career_goal": "",
"progress_points": 0,
"completed_tasks": [],
"upcoming_events": [],
"routine_history": [],
"daily_emotions": [],
"resume_path": "",
"portfolio_path": "",
"recommendations": [],
"chat_history": [],
"joined_date": datetime.now().strftime("%Y-%m-%d")
}
save_user_database(db)
return db['users'][user_id]
def update_user_profile(user_id, updates):
"""Update user profile with new information"""
db = load_user_database()
if user_id in db['users']:
for key, value in updates.items():
db['users'][user_id][key] = value
save_user_database(db)
return db['users'][user_id]
def add_task_to_user(user_id, task):
"""Add a new task to user's completed tasks"""
db = load_user_database()
if user_id in db['users']:
if 'completed_tasks' not in db['users'][user_id]:
db['users'][user_id]['completed_tasks'] = []
task_with_date = {
"task": task,
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
db['users'][user_id]['completed_tasks'].append(task_with_date)
db['users'][user_id]['progress_points'] += random.randint(10, 25)
save_user_database(db)
return db['users'][user_id]
def add_emotion_record(user_id, emotion):
"""Add a new emotion record to user's daily emotions"""
db = load_user_database()
if user_id in db['users']:
if 'daily_emotions' not in db['users'][user_id]:
db['users'][user_id]['daily_emotions'] = []
emotion_record = {
"emotion": emotion,
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
db['users'][user_id]['daily_emotions'].append(emotion_record)
db['users'][user_id]['current_emotion'] = emotion
save_user_database(db)
return db['users'][user_id]
def add_routine_to_user(user_id, routine):
"""Add a new routine to user's routine history"""
db = load_user_database()
if user_id in db['users']:
if 'routine_history' not in db['users'][user_id]:
db['users'][user_id]['routine_history'] = []
routine_with_date = {
"routine": routine,
"start_date": datetime.now().strftime("%Y-%m-%d"),
"end_date": (datetime.now() + timedelta(days=routine.get('days', 7))).strftime("%Y-%m-%d"),
"completion": 0
}
db['users'][user_id]['routine_history'].append(routine_with_date)
save_user_database(db)
return db['users'][user_id]
def save_user_resume(user_id, resume_text):
"""Save user's resume to file and update profile"""
# Create filename
filename = f"{user_id}_resume.txt"
filepath = os.path.join(RESUME_FOLDER, filename)
# Save resume text to file
with open(filepath, 'w') as file:
file.write(resume_text)
# Update user profile
update_user_profile(user_id, {"resume_path": filepath})
return filepath
def save_user_portfolio(user_id, portfolio_content):
"""Save user's portfolio info to file and update profile"""
# Create filename
filename = f"{user_id}_portfolio.json"
filepath = os.path.join(PORTFOLIO_FOLDER, filename)
# Save portfolio content to file
with open(filepath, 'w') as file:
json.dump(portfolio_content, file, indent=4)
# Update user profile
update_user_profile(user_id, {"portfolio_path": filepath})
return filepath
def add_recommendation_to_user(user_id, recommendation):
"""Add a new recommendation to user's recommendations list"""
db = load_user_database()
if user_id in db['users']:
if 'recommendations' not in db['users'][user_id]:
db['users'][user_id]['recommendations'] = []
recommendation_with_date = {
"recommendation": recommendation,
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"status": "pending" # pending, completed, dismissed
}
db['users'][user_id]['recommendations'].append(recommendation_with_date)
save_user_database(db)
return db['users'][user_id]
def add_chat_message(user_id, role, message):
"""Add a message to the user's chat history"""
db = load_user_database()
if user_id in db['users']:
if 'chat_history' not in db['users'][user_id]:
db['users'][user_id]['chat_history'] = []
chat_message = {
"role": role, # user or assistant
"message": message,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
db['users'][user_id]['chat_history'].append(chat_message)
save_user_database(db)
return db['users'][user_id]
# API Helper Functions
def search_jobs_with_serper(query, location, max_results=5):
"""Search for job opportunities using Serper API"""
try:
headers = {
'X-API-KEY': SERPER_API_KEY,
'Content-Type': 'application/json'
}
params = {
'q': f"{query} jobs in {location}",
'num': max_results
}
response = requests.get(
'https://serper.dev/search',
headers=headers,
params=params
)
if response.status_code == 200:
data = response.json()
# Extract job listings from search results
job_results = []
# Process organic results
if 'organic' in data:
for item in data['organic']:
if 'title' in item and 'link' in item and 'snippet' in item:
# Check if it looks like a job listing
if any(keyword in item['title'].lower() for keyword in ['job', 'career', 'position', 'hiring', 'work']):
job_results.append({
'title': item['title'],
'company': extract_company_from_title(item['title']),
'description': item['snippet'],
'link': item['link'],
'location': location,
'date_posted': 'Recent' # Serper doesn't provide this directly
})
return job_results
else:
logger.error(f"Error from Serper API: {response.status_code} - {response.text}")
return []
except Exception as e:
logger.error(f"Exception in search_jobs_with_serper: {str(e)}")
return []
def extract_company_from_title(title):
"""Extract company name from job title if possible"""
# This is a simple heuristic and can be improved
if ' at ' in title:
return title.split(' at ')[1].strip()
if ' - ' in title:
return title.split(' - ')[1].strip()
return "Unknown Company"
def get_ai_response(user_id, user_input, context=None, generate_recommendations=True):
"""Get AI response using Google GenAI"""
try:
user_profile = get_user_profile(user_id)
system_instruction = """
You are Aishura, an emotionally intelligent AI career assistant. Your goal is to empathize with the user's emotions
and provide realistic information and actionable suggestions. Follow this structure:
1. Recognize and acknowledge the user's emotion
2. Respond with high-empathy message
3. Suggest specific action based on their input
4. Offer document support, job opportunities, or personalized routine
Remember to be proactive and preemptive - suggest actions before the user asks. Your goal is to provide
end-to-end support for the user's career journey, from emotional support to concrete action.
If the user has shared a resume or portfolio, refer to insights from those documents to provide
personalized guidance.
"""
# Build conversation context
contents = []
# Add user profile information as context
profile_context = f"""
User Profile Information:
- Name: {user_profile.get('name', '')}
- Current emotion: {user_profile.get('current_emotion', '')}
- Career goal: {user_profile.get('career_goal', '')}
- Location: {user_profile.get('location', '')}
"""
# Add resume context if available
if user_profile.get('resume_path') and os.path.exists(user_profile.get('resume_path')):
try:
with open(user_profile.get('resume_path'), 'r') as file:
resume_text = file.read()
profile_context += f"\nUser Resume Summary: The user has shared their resume. They have experience in {resume_text[:100]}..."
except Exception as e:
logger.error(f"Error reading resume: {str(e)}")
# Add portfolio context if available
if user_profile.get('portfolio_path') and os.path.exists(user_profile.get('portfolio_path')):
try:
with open(user_profile.get('portfolio_path'), 'r') as file:
portfolio_data = json.load(file)
profile_context += f"\nUser Portfolio: The user has shared their portfolio with URL: {portfolio_data.get('url', 'Not provided')}."
except Exception as e:
logger.error(f"Error reading portfolio: {str(e)}")
# Start with context
user_context = types.Content(
role="user",
parts=[types.Part.from_text(profile_context)]
)
contents.append(user_context)
# Add previous context if provided
if context:
for msg in context:
if msg["role"] == "user":
contents.append(types.Content(
role="user",
parts=[types.Part.from_text(msg["message"])]
))
else:
contents.append(types.Content(
role="model",
parts=[types.Part.from_text(msg["message"])]
))
# Add current user input
contents.append(types.Content(
role="user",
parts=[types.Part.from_text(user_input)]
))
# Configure tools
tools = [job_tool, document_tool, routine_tool, resume_tool, portfolio_tool]
# Get response
response = client.models.generate_content(
model=MODEL_ID,
contents=contents,
system_instruction=system_instruction,
tools=tools,
generation_config=types.GenerationConfig(
temperature=0.7,
max_output_tokens=2048,
top_p=0.95,
top_k=40
)
)
ai_response_text = response.text
# Log the message in chat history
add_chat_message(user_id, "user", user_input)
add_chat_message(user_id, "assistant", ai_response_text)
# Generate recommendations if enabled
if generate_recommendations:
gen_recommendations(user_id, user_input, ai_response_text)
return ai_response_text
except Exception as e:
logger.error(f"Error in get_ai_response: {str(e)}")
return "I apologize, but I'm having trouble processing your request right now. Please try again later."
def gen_recommendations(user_id, user_input, ai_response):
"""Generate recommendations based on conversation"""
try:
user_profile = get_user_profile(user_id)
prompt = f"""
Based on the following conversation between a user and Aishura (an AI career assistant),
generate 1-3 specific, actionable recommendations for the user's next steps in their career journey.
User Profile:
- Current emotion: {user_profile.get('current_emotion', '')}
- Career goal: {user_profile.get('career_goal', '')}
- Location: {user_profile.get('location', '')}
Recent Conversation:
User: {user_input}
Aishura: {ai_response}
Generate specific, actionable recommendations in JSON format:
```json
[
{{
"title": "Brief recommendation title",
"description": "Detailed recommendation description",
"action_type": "job_search|skill_building|networking|resume|portfolio|interview_prep|other",
"priority": "high|medium|low"
}}
]
```
Focus on immediate, practical next steps that align with the user's goals and emotional state.
"""
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt
)
recommendation_text = response.text
# Extract JSON from response
try:
# Find JSON content between ```json and ``` if present
if "```json" in recommendation_text and "```" in recommendation_text.split("```json")[1]:
json_str = recommendation_text.split("```json")[1].split("```")[0].strip()
else:
# Otherwise try to find anything that looks like JSON array
import re
json_match = re.search(r'(\[.*\])', recommendation_text, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
json_str = recommendation_text
recommendations = json.loads(json_str)
# Add recommendations to user profile
for rec in recommendations:
add_recommendation_to_user(user_id, rec)
return recommendations
except json.JSONDecodeError:
logger.error(f"Failed to parse JSON from AI response: {recommendation_text}")
return []
except Exception as e:
logger.error(f"Error in gen_recommendations: {str(e)}")
return []
def create_personalized_routine_with_ai(user_id, emotion, goal, available_time=60, days=7):
"""Create a personalized routine using AI"""
try:
user_profile = get_user_profile(user_id)
prompt = f"""
Create a personalized {days}-day career development routine for a user who is feeling {emotion} and has a goal to {goal}.
They have about {available_time} minutes per day to dedicate to this routine.
For each day, suggest 1-3 specific tasks that will help them make progress toward their goal while considering their emotional state.
For each task provide:
1. Task name
2. Duration in minutes
3. Points value (between 10-50)
4. A brief description of why this task is valuable
Format the routine as a JSON object with this structure:
```json
{{
"name": "Routine name",
"description": "Brief description of the routine",
"days": {days},
"daily_tasks": [
{{
"day": 1,
"tasks": [
{{
"name": "Task name",
"points": 20,
"duration": 30,
"description": "Why this task is valuable"
}}
]
}}
]
}}
```
"""
# Use resume and portfolio info if available
if user_profile.get('resume_path') and os.path.exists(user_profile.get('resume_path')):
try:
with open(user_profile.get('resume_path'), 'r') as file:
resume_text = file.read()
prompt += f"\n\nTailor the routine based on the user's resume. Here's a summary: {resume_text[:500]}..."
except Exception as e:
logger.error(f"Error reading resume: {str(e)}")
if user_profile.get('portfolio_path') and os.path.exists(user_profile.get('portfolio_path')):
try:
with open(user_profile.get('portfolio_path'), 'r') as file:
portfolio_data = json.load(file)
prompt += f"\n\nConsider the user's portfolio when creating the routine. Portfolio URL: {portfolio_data.get('url', 'Not provided')}"
except Exception as e:
logger.error(f"Error reading portfolio: {str(e)}")
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt
)
routine_text = response.text
# Extract JSON portion from the response
try:
# Find JSON content between ```json and ``` if present
if "```json" in routine_text and "```" in routine_text.split("```json")[1]:
json_str = routine_text.split("```json")[1].split("```")[0].strip()
else:
# Otherwise try to find anything that looks like JSON
import re
json_match = re.search(r'(\{.*\})', routine_text, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
json_str = routine_text
routine = json.loads(json_str)
# Add to user's routines
user_profile = add_routine_to_user(user_id, routine)
return routine
except json.JSONDecodeError:
logger.error(f"Failed to parse JSON from AI response: {routine_text}")
# Fallback to a basic routine
return generate_basic_routine(emotion, goal, available_time, days)
except Exception as e:
logger.error(f"Error in create_personalized_routine_with_ai: {str(e)}")
# Fallback to a basic routine
return generate_basic_routine(emotion, goal, available_time, days)
def generate_basic_routine(emotion, goal, available_time=60, days=7):
"""Generate a basic routine as fallback"""
routine_types = {
"job_search": [
{"name": "Research target companies", "points": 10, "duration": 20, "description": "Identify potential employers that align with your career goals"},
{"name": "Update LinkedIn profile", "points": 15, "duration": 30, "description": "Keep your professional presence current and compelling"},
{"name": "Practice interview questions", "points": 20, "duration": 45, "description": "Build confidence and prepare for upcoming opportunities"},
{"name": "Reach out to a contact", "points": 25, "duration": 15, "description": "Grow your network and gather industry insights"}
],
"skill_building": [
{"name": "Complete one tutorial", "points": 20, "duration": 60, "description": "Develop practical skills in your field"},
{"name": "Read industry article", "points": 10, "duration": 15, "description": "Stay current with trends and developments"},
{"name": "Work on portfolio project", "points": 30, "duration": 90, "description": "Create tangible evidence of your abilities"},
{"name": "Watch expert talk", "points": 15, "duration": 30, "description": "Learn from leaders in your field"}
],
"motivation": [
{"name": "Write in gratitude journal", "points": 10, "duration": 10, "description": "Cultivate a positive mindset to enhance motivation"},
{"name": "Set 3 goals for the day", "points": 15, "duration": 15, "description": "Focus your energy on achievable tasks"},
{"name": "Exercise break", "points": 20, "duration": 20, "description": "Boost energy and mood with physical activity"},
{"name": "Reflect on progress", "points": 15, "duration": 15, "description": "Acknowledge achievements and identify next steps"}
]
}
# Select routine type based on goal
if "job" in goal.lower() or "company" in goal.lower():
routine_type = "job_search"
elif "skill" in goal.lower() or "learn" in goal.lower():
routine_type = "skill_building"
else:
# Default to motivation if feeling negative emotions
if emotion.lower() in ["unmotivated", "anxious", "confused", "overwhelmed", "discouraged"]:
routine_type = "motivation"
else:
routine_type = random.choice(list(routine_types.keys()))
# Create daily plan
daily_tasks = []
for day in range(1, days + 1):
# Randomly select 1-3 tasks for the day that fit within available time
available_tasks = routine_types[routine_type].copy()
random.shuffle(available_tasks)
day_tasks = []
remaining_time = available_time
for task in available_tasks:
if task["duration"] <= remaining_time and len(day_tasks) < 3:
day_tasks.append(task)
remaining_time -= task["duration"]
if remaining_time < 10 or len(day_tasks) >= 3:
break
daily_tasks.append({
"day": day,
"tasks": day_tasks
})
routine = {
"name": f"{days}-Day {routine_type.replace('_', ' ').title()} Plan",
"description": f"A personalized routine to help you {goal} while managing feelings of {emotion}.",
"days": days,
"daily_tasks": daily_tasks
}
return routine
def generate_document_template_with_ai(document_type, career_field="", experience_level=""):
"""Generate document templates using AI"""
try:
prompt = f"""
Create a detailed template for a {document_type} for someone in the {career_field} field
with {experience_level} experience level.
The template should include all necessary sections and sample content that can be replaced.
Format it in markdown.
"""
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt
)
return response.text
except Exception as e:
logger.error(f"Error in generate_document_template_with_ai: {str(e)}")
return f"Error generating {document_type} template. Please try again later."
def analyze_resume_with_ai(user_id, resume_text):
"""Analyze resume with AI and provide feedback"""
try:
user_profile = get_user_profile(user_id)
prompt = f"""
Analyze the following resume for a user who has the career goal of: {user_profile.get('career_goal', 'improving their career')}
Resume Text:
{resume_text}
Provide detailed feedback on:
1. Overall strengths and weaknesses
2. Format and organization
3. Content effectiveness for their career goal
4. Specific improvement suggestions
5. Keywords and skills that should be highlighted
Format your analysis with markdown headings and bullet points.
"""
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt
)
# Save resume
save_user_resume(user_id, resume_text)
return response.text
except Exception as e:
logger.error(f"Error in analyze_resume_with_ai: {str(e)}")
return "I apologize, but I'm having trouble analyzing your resume right now. Please try again later."
def analyze_portfolio_with_ai(user_id, portfolio_url, portfolio_description):
"""Analyze portfolio with AI and provide feedback"""
try:
user_profile = get_user_profile(user_id)
prompt = f"""
Analyze the following portfolio for a user who has the career goal of: {user_profile.get('career_goal', 'improving their career')}
Portfolio URL: {portfolio_url}
Portfolio Description: {portfolio_description}
Based on the description provided, analyze:
1. How well the portfolio aligns with their career goal
2. Strengths of the portfolio
3. Areas for improvement
4. Specific suggestions to enhance the portfolio
5. How to better showcase skills relevant to their goal
Format your analysis with markdown headings and bullet points.
"""
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt
)
# Save portfolio info
portfolio_content = {
"url": portfolio_url,
"description": portfolio_description
}
save_user_portfolio(user_id, portfolio_content)
return response.text
except Exception as e:
logger.error(f"Error in analyze_portfolio_with_ai: {str(e)}")
return "I apologize, but I'm having trouble analyzing your portfolio right now. Please try again later."
# Chart and visualization functions
def create_emotion_chart(user_id):
"""Create a chart of user's emotions over time"""
user_profile = get_user_profile(user_id)
emotion_records = user_profile.get('daily_emotions', [])
if not emotion_records:
# Return empty chart if no data
fig = px.line(title="Emotion Tracking: No data available yet")
return fig
# Prepare data
emotion_values = {
"Unmotivated": 1,
"Anxious": 2,
"Confused": 3,
"Discouraged": 4,
"Overwhelmed": 5,
"Excited": 6
}
dates = []
emotion_scores = []
emotion_names = []
for record in emotion_records:
dates.append(datetime.strptime(record['date'], "%Y-%m-%d %H:%M:%S"))
emotion = record['emotion']
emotion_names.append(emotion)
emotion_scores.append(emotion_values.get(emotion, 3))
df = pd.DataFrame({
'Date': dates,
'Emotion Score': emotion_scores,
'Emotion': emotion_names
})
# Create chart
fig = px.line(df, x='Date', y='Emotion Score', markers=True,
labels={"Emotion Score": "Emotional State"},
title="Your Emotional Journey")
# Add emotion names as hover text
fig.update_traces(hovertemplate='%{x}<br>Feeling: %{text}', text=df['Emotion'])
# Customize y-axis to show emotion names instead of numbers
fig.update_yaxes(
tickvals=list(emotion_values.values()),
ticktext=list(emotion_values.keys())
)
return fig
def create_progress_chart(user_id):
"""Create a chart showing user's progress over time"""
user_profile = get_user_profile(user_id)
tasks = user_profile.get('completed_tasks', [])
if not tasks:
# Return empty chart if no data
fig = px.line(title="Progress Tracking: No data available yet")
return fig
# Prepare data
dates = []
points = []
cumulative_points = 0
task_labels = []
for task in tasks:
dates.append(datetime.strptime(task['date'], "%Y-%m-%d %H:%M:%S"))
# Increment points (assuming each task has inherent points)
cumulative_points += 20
points.append(cumulative_points)
task_labels.append(task['task'])
df = pd.DataFrame({
'Date': dates,
'Points': points,
'Task': task_labels
})
# Create chart
fig = px.line(df, x='Date', y='Points', markers=True,
title="Your Career Journey Progress")
# Add task names as hover text
fig.update_traces(hovertemplate='%{x}<br>Points: %{y}<br>Task: %{text}', text=df['Task'])
return fig
def create_routine_completion_gauge(user_id):
"""Create a gauge chart showing routine completion percentage"""
user_profile = get_user_profile(user_id)
routines = user_profile.get('routine_history', [])
if not routines:
# Return empty chart if no data
fig = go.Figure()
fig.add_annotation(text="No active routines yet", showarrow=False)
return fig
# Get the most recent routine
latest_routine = routines[-1]
completion = latest_routine.get('completion', 0)
# Create gauge chart
fig = go.Figure(go.Indicator(
mode = "gauge+number",
value = completion,
domain = {'x': [0, 1], 'y': [0, 1]},
title = {'text': "Current Routine Completion"},
gauge = {
'axis': {'range': [None, 100]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, 30], 'color': "lightgray"},
{'range': [30, 70], 'color': "gray"},
{'range': [70, 100], 'color': "darkgray"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 90
}
}
))
return fig
def create_skill_radar_chart(user_id):
"""Create a radar chart of user's skills based on resume analysis"""
user_profile = get_user_profile(user_id)
# If no resume, return empty chart
if not user_profile.get('resume_path') or not os.path.exists(user_profile.get('resume_path')):
fig = go.Figure()
fig.add_annotation(text="No resume data available yet", showarrow=False)
return fig
# Read resume
try:
with open(user_profile.get('resume_path'), 'r') as file:
resume_text = file.read()
except Exception as e:
logger.error(f"Error reading resume: {str(e)}")
fig = go.Figure()
fig.add_annotation(text="Error reading resume data", showarrow=False)
return fig
# Use AI to extract and score skills
prompt = f"""
Based on the following resume, identify 5-8 key skills and rate them on a scale of 1-10.
Resume:
{resume_text[:2000]}...
Return the results as a JSON object with this structure:
```json
{{
"skills": [
{{"name": "Skill Name", "score": 7}},
{{"name": "Another Skill", "score": 9}}
]
}}
```
"""
try:
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt
)
skill_text = response.text
# Extract JSON
if "```json" in skill_text and "```" in skill_text.split("```json")[1]:
json_str = skill_text.split("```json")[1].split("```")[0].strip()
else:
import re
json_match = re.search(r'(\{.*\})', skill_text, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
json_str = skill_text
skill_data = json.loads(json_str)
# Create radar chart
if 'skills' in skill_data and skill_data['skills']:
skills = skill_data['skills']
# Prepare data for radar chart
categories = [skill['name'] for skill in skills]
values = [skill['score'] for skill in skills]
# Add the first point at the end to close the loop
categories.append(categories[0])
values.append(values[0])
fig = go.Figure()
fig.add_trace(go.Scatterpolar(
r=values,
theta=categories,
fill='toself',
name='Skills'
))
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 10]
)
),
showlegend=False,
title="Skill Assessment Based on Resume"
)
return fig
else:
fig = go.Figure()
fig.add_annotation(text="Could not extract skills from resume", showarrow=False)
return fig
except Exception as e:
logger.error(f"Error creating skill radar chart: {str(e)}")
fig = go.Figure()
fig.add_annotation(text="Error analyzing skills", showarrow=False)
return fig
# Gradio interface components
def create_interface():
"""Create the Gradio interface for Aishura MVP"""
# Generate a unique user ID for this session
session_user_id = str(uuid.uuid4())
# Welcome page
def welcome(name, location, emotion, goal):
if not name or not location or not emotion or not goal:
return ("Please fill out all fields to continue.",
gr.update(visible=True),
gr.update(visible=False))
# Update user profile
update_user_profile(session_user_id, {
"name": name,
"location": location,
"career_goal": goal
})
# Record emotion
add_emotion_record(session_user_id, emotion)
# Generate initial AI response
response = get_ai_response(
session_user_id,
f"I'm {name} from {location}. I'm feeling {emotion} and my career goal is to {goal}."
)
return (response,
gr.update(visible=False),
gr.update(visible=True))
# Chat function
def chat(message, history):
# Get user profile
user_profile = get_user_profile(session_user_id)
# Convert history to the format expected by get_ai_response
context = []
for h in history:
context.append({"role": "user", "message": h[0]})
context.append({"role": "assistant", "message": h[1]})
# Get AI response
response = get_ai_response(session_user_id, message, context)
# Return updated history and empty message
history.append((message, response))
return history, ""
# Function to search for jobs
def search_jobs_interface(query, location, max_results=5):
jobs = search_jobs_with_serper(query, location, int(max_results))
if not jobs:
return "No job opportunities found. Try adjusting your search terms."
result = "## Job Opportunities Found\n\n"
for i, job in enumerate(jobs, 1):
result += f"### {i}. {job['title']}\n"
result += f"**Company:** {job['company']}\n"
result += f"**Location:** {job['location']}\n"
result += f"**Description:** {job['description']}\n"
result += f"**Link:** [Apply Here]({job['link']})\n\n"
return result
# Function to generate document templates
def generate_template(document_type, career_field, experience_level):
template = generate_document_template_with_ai(document_type, career_field, experience_level)
return template
# Function to create personal routine
def create_personal_routine(emotion, goal, available_time, days):
routine = create_personalized_routine_with_ai(
session_user_id, emotion, goal, int(available_time), int(days)
)
# Format routine for display
result = f"# Your {routine['name']}\n\n"
result += f"{routine['description']}\n\n"
for day_plan in routine['daily_tasks']:
result += f"## Day {day_plan['day']}\n\n"
for task in day_plan['tasks']:
result += f"- **{task['name']}** ({task['duration']} mins, {task['points']} points)\n"
result += f" *{task['description']}*\n\n"
return result
# Function to analyze resume
def analyze_resume_interface(resume_text):
if not resume_text:
return "Please enter your resume text."
analysis = analyze_resume_with_ai(session_user_id, resume_text)
# Update skill chart
skill_fig = create_skill_radar_chart(session_user_id)
return analysis, skill_fig
# Function to analyze portfolio
def analyze_portfolio_interface(portfolio_url, portfolio_description):
if not portfolio_description:
return "Please enter a description of your portfolio."
analysis = analyze_portfolio_with_ai(session_user_id, portfolio_url, portfolio_description)
return analysis
# Function to mark a task as complete
def complete_task(task_name):
if not task_name:
return "Please enter a task name."
user_profile = add_task_to_user(session_user_id, task_name)
# Update completion percentage of current routine
if user_profile.get('routine_history'):
latest_routine = user_profile['routine_history'][-1]
# Simple approach: increase completion by random amount between 5-15%
new_completion = min(100, latest_routine.get('completion', 0) + random.randint(5, 15))
latest_routine['completion'] = new_completion
update_user_profile(session_user_id, {"routine_history": user_profile['routine_history']})
# Create updated charts
emotion_fig = create_emotion_chart(session_user_id)
progress_fig = create_progress_chart(session_user_id)
gauge_fig = create_routine_completion_gauge(session_user_id)
return (
f"Task '{task_name}' completed! You earned {random.randint(10, 25)} points.",
"",
emotion_fig,
progress_fig,
gauge_fig
)
# Function to update emotion
def update_emotion(emotion):
add_emotion_record(session_user_id, emotion)
# Create updated emotion chart
emotion_fig = create_emotion_chart(session_user_id)
return (
f"Your emotional state has been updated to: {emotion}",
emotion_fig
)
# Function to display recommendations
def display_recommendations():
user_profile = get_user_profile(session_user_id)
recommendations = user_profile.get('recommendations', [])
if not recommendations:
return "No recommendations available yet. Continue chatting with Aishura to receive personalized suggestions."
# Show the most recent 5 recommendations
recent_recs = recommendations[-5:]
result = "# Your Personalized Recommendations\n\n"
for i, rec in enumerate(recent_recs, 1):
recommendation = rec['recommendation']
result += f"## {i}. {recommendation['title']}\n\n"
result += f"{recommendation['description']}\n\n"
result += f"**Priority:** {recommendation['priority'].title()}\n"
result += f"**Type:** {recommendation['action_type'].replace('_', ' ').title()}\n\n"
result += "---\n\n"
return result
# Create the interface
with gr.Blocks(theme=gr.themes.Soft()) as app:
gr.Markdown("# Aishura - Your AI Career Assistant")
# Welcome page
with gr.Group(visible=True) as welcome_group:
gr.Markdown("## Welcome to Aishura")
gr.Markdown("Let's start by getting to know you a little better.")
name_input = gr.Textbox(label="Your Name")
location_input = gr.Textbox(label="Your Location (City/Country)")
emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling today?")
goal_dropdown = gr.Dropdown(choices=GOAL_TYPES, label="What's your career goal?")
welcome_button = gr.Button("Get Started")
welcome_output = gr.Markdown()
# Main interface
with gr.Group(visible=False) as main_interface:
with gr.Tabs() as tabs:
# Chat tab
with gr.TabItem("Chat with Aishura"):
with gr.Row():
with gr.Column(scale=2):
chatbot = gr.Chatbot(height=500, avatar_images=["π€", "π€"])
msg = gr.Textbox(show_label=False, placeholder="Type your message here...", container=False)
with gr.Column(scale=1):
gr.Markdown("## Your Recommendations")
recommendation_output = gr.Markdown()
refresh_recs_button = gr.Button("Refresh Recommendations")
msg.submit(chat, [msg, chatbot], [chatbot, msg])
refresh_recs_button.click(display_recommendations, [], recommendation_output)
# Profile and Career Analysis tab
with gr.TabItem("Profile & Analysis"):
with gr.Tabs() as analysis_tabs:
# Resume Analysis
with gr.TabItem("Resume Analysis"):
gr.Markdown("## Resume Analysis")
resume_text = gr.Textbox(label="Paste your resume here", lines=10, placeholder="Copy and paste your entire resume here for analysis...")
analyze_resume_button = gr.Button("Analyze Resume")
resume_output = gr.Markdown()
skill_chart = gr.Plot(label="Skill Assessment")
analyze_resume_button.click(
analyze_resume_interface,
[resume_text],
[resume_output, skill_chart]
)
# Portfolio Analysis
with gr.TabItem("Portfolio Analysis"):
gr.Markdown("## Portfolio Analysis")
portfolio_url = gr.Textbox(label="Portfolio URL", placeholder="https://your-portfolio-website.com")
portfolio_description = gr.Textbox(label="Describe your portfolio", lines=5, placeholder="Describe the content, structure, and purpose of your portfolio...")
analyze_portfolio_button = gr.Button("Analyze Portfolio")
portfolio_output = gr.Markdown()
analyze_portfolio_button.click(
analyze_portfolio_interface,
[portfolio_url, portfolio_description],
portfolio_output
)
# Job Search tab
with gr.TabItem("Find Opportunities"):
gr.Markdown("## Search for Job Opportunities")
job_query = gr.Textbox(label="What kind of job are you looking for?")
job_location = gr.Textbox(label="Location")
job_results = gr.Slider(minimum=5, maximum=20, value=10, step=5, label="Number of Results")
search_button = gr.Button("Search")
job_output = gr.Markdown()
search_button.click(search_jobs_interface, [job_query, job_location, job_results], job_output)
# Document Templates tab
with gr.TabItem("Document Templates"):
gr.Markdown("## Generate Document Templates")
doc_type = gr.Dropdown(
choices=["Resume", "Cover Letter", "Self-Introduction", "LinkedIn Profile", "Portfolio", "Interview Preparation"],
label="Document Type"
)
career_field = gr.Textbox(label="Career Field/Industry")
experience = gr.Dropdown(
choices=["Entry Level", "Mid-Career", "Senior"],
label="Experience Level"
)
template_button = gr.Button("Generate Template")
template_output = gr.Markdown()
template_button.click(generate_template, [doc_type, career_field, experience], template_output)
# Personal Routine tab
with gr.TabItem("Personal Routine"):
gr.Markdown("## Create Your Personal Development Routine")
routine_emotion = gr.Dropdown(choices=EMOTIONS, label="Current Emotional State")
routine_goal = gr.Textbox(label="What specific goal are you working toward?")
time_available = gr.Slider(minimum=15, maximum=120, value=60, step=15, label="Minutes Available Per Day")
routine_days = gr.Slider(minimum=3, maximum=30, value=7, step=1, label="Length of Routine (Days)")
routine_button = gr.Button("Create Routine")
routine_output = gr.Markdown()
routine_button.click(create_personal_routine,
[routine_emotion, routine_goal, time_available, routine_days],
routine_output)
# Progress Tracking tab
with gr.TabItem("Track Progress"):
with gr.Row():
with gr.Column():
gr.Markdown("## Mark Tasks as Complete")
task_input = gr.Textbox(label="Enter Task Name")
complete_button = gr.Button("Mark as Complete")
task_output = gr.Markdown()
with gr.Column():
gr.Markdown("## Update Your Emotional State")
new_emotion = gr.Dropdown(choices=EMOTIONS, label="How are you feeling now?")
emotion_button = gr.Button("Update")
emotion_output = gr.Markdown()
with gr.Row():
with gr.Column():
emotion_chart = gr.Plot(label="Emotional Journey")
with gr.Column():
progress_chart = gr.Plot(label="Progress Journey")
with gr.Row():
gauge_chart = gr.Plot(label="Routine Completion")
complete_button.click(
complete_task,
[task_input],
[task_output, task_input, emotion_chart, progress_chart, gauge_chart]
)
emotion_button.click(
update_emotion,
[new_emotion],
[emotion_output, emotion_chart]
)
# Welcome button action
welcome_button.click(
welcome,
[name_input, location_input, emotion_dropdown, goal_dropdown],
[welcome_output, welcome_group, main_interface]
)
# Load initial recommendations
app.load(
display_recommendations,
[],
recommendation_output
)
return app
# Main function to launch the app
def main():
app = create_interface()
app.launch(share=True)
if __name__ == "__main__":
main() |