AIShurA / app.py
ans123's picture
Update app.py
9eeef04 verified
# filename: app_groq_serper_v5.py
import gradio as gr
import pandas as pd
import numpy as np
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 # For Serper API
from typing import List, Dict, Any, Optional, Generator
import logging
from dotenv import load_dotenv
import uuid
import re
# --- Groq Integration ---
from groq import Groq, RateLimitError, APIError, APIConnectionError, APITimeoutError, AuthenticationError
# --- 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 ---
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
if not GROQ_API_KEY:
logger.warning("GROQ_API_KEY not found. AI features will not work.")
else:
logger.info("Groq API Key found.")
if not SERPER_API_KEY:
logger.warning("SERPER_API_KEY not found. Live web search features will not work.")
else:
logger.info("Serper API Key found.")
# --- Initialize the Groq client ---
try:
if GROQ_API_KEY:
client = Groq(api_key=GROQ_API_KEY)
logger.info("Groq client initialized successfully.")
else:
client = None
logger.error("Failed to initialize Groq client: API key is missing.")
except Exception as e:
logger.error(f"Failed to initialize Groq client: {e}")
client = None
# --- Model configuration ---
MODEL_ID = "llama3-70b-8192" # ** Updated model ID **
# --- Constants ---
# Using the same enhanced constants from previous versions
EMOTIONS = ["Unmotivated 😩", "Anxious πŸ˜₯", "Confused πŸ€”", "Excited πŸŽ‰", "Overwhelmed 🀯", "Discouraged πŸ˜”", "Hopeful ✨", "Focused 😎", "Stuck 🧱"]
GOAL_TYPES = [
"Get a job (Big Company) 🏒", "Get a job (Startup) 🌱", "Find an Internship πŸŽ“", "Freelance/Contract Work πŸ’Ό",
"Change Careers πŸš€", "Improve Specific Skills πŸ’‘", "Build Professional Network 🀝", "Leadership Development πŸ“ˆ", "Explore Options πŸ€”"
]
USER_DB_PATH = "user_database_v5.json" # New DB file for this version
RESUME_FOLDER = "user_resumes_v5"
PORTFOLIO_FOLDER = "user_portfolios_v5"
os.makedirs(RESUME_FOLDER, exist_ok=True)
os.makedirs(PORTFOLIO_FOLDER, exist_ok=True)
# --- Tool Definitions for Groq API (Mirrors OpenAI format) ---
# Groq generally uses the OpenAI-compatible tool format.
tools_list_groq = [
{
"type": "function",
"function": {
"name": "generate_document_template",
"description": "Generate a document template (like a resume or cover letter) based on type, career field, and experience level.",
"parameters": { "type": "object", "properties": { "document_type": {"type": "string", "description": "e.g., Resume, Cover Letter, LinkedIn Summary"}, "career_field": {"type": "string", "description": "Target industry or field"}, "experience_level": {"type": "string", "description": "e.g., Entry, Mid, Senior, Student"} }, "required": ["document_type"] },
}
},
{
"type": "function",
"function": {
"name": "create_personalized_routine",
"description": "Create a personalized daily or weekly career development routine based on the user's current emotion, goals, and available time.",
"parameters": { "type": "object", "properties": { "emotion": {"type": "string", "description": "User's current primary emotion"}, "goal": {"type": "string", "description": "User's primary career goal"}, "available_time_minutes": {"type": "integer", "description": "Average minutes per day user can dedicate"}, "routine_length_days": {"type": "integer", "description": "Desired length of the routine in days (e.g., 7 for weekly)"} }, "required": ["emotion", "goal"] },
}
},
{
"type": "function",
"function": {
"name": "analyze_resume",
"description": "Analyze the provided resume text and provide feedback, comparing it against the user's stated career goal. Provides strengths, weaknesses, and suggestions.",
"parameters": { "type": "object", "properties": { "resume_text": {"type": "string", "description": "The full text content of the user's resume"}, "career_goal": {"type": "string", "description": "The specific career goal to analyze against"} }, "required": ["resume_text", "career_goal"] },
}
},
{
"type": "function",
"function": {
"name": "analyze_portfolio",
"description": "Analyze a user's portfolio based on a URL (if provided) and a description, offering feedback relative to their career goal.",
"parameters": { "type": "object", "properties": { "portfolio_url": {"type": "string", "description": "URL link to the online portfolio (optional)"}, "portfolio_description": {"type": "string", "description": "User's description of the portfolio content and purpose"}, "career_goal": {"type": "string", "description": "The specific career goal to analyze against"} }, "required": ["portfolio_description", "career_goal"] },
}
},
{
"type": "function",
"function": {
"name": "extract_and_rate_skills_from_resume",
"description": "Extracts key skills from resume text and rates them on a scale of 1-10 based on apparent proficiency shown in the resume. Useful for identifying strengths and gaps.",
"parameters": { "type": "object", "properties": { "resume_text": {"type": "string", "description": "The full text content of the user's resume"}, "max_skills": {"type": "integer", "description": "Maximum number of skills to extract (default 8)"} }, "required": ["resume_text"] },
}
},
{
"type": "function",
"function": {
"name": "search_jobs_courses_skills",
"description": "Search the web using Serper API for relevant job openings, online courses, or skills development resources based on the user's goals, location, and potentially identified skill gaps.",
"parameters": { "type": "object", "properties": { "search_query": {"type": "string", "description": "The specific search query (e.g., 'remote data analyst jobs in California', 'online Python courses for beginners', 'project management certifications')"}, "search_type": {"type": "string", "description": "Type of search: 'jobs', 'courses', 'skills', or 'general'"}, "location": {"type": "string", "description": "Geographical location for the search (if applicable, e.g., 'London, UK')"} }, "required": ["search_query", "search_type"] },
}
}
]
# --- User Database Functions (Using OpenAI/Groq-compatible format) ---
# Keep the load/save/get/update functions from v4 as the chat history format is compatible.
def load_user_database():
# (Identical to v4 - handles OpenAI/Groq compatible format)
try:
# Check if the file exists and is not empty
if not os.path.exists(USER_DB_PATH) or os.path.getsize(USER_DB_PATH) == 0:
logger.info(f"DB file '{USER_DB_PATH}' not found or empty. Creating new.")
db = {'users': {}}
save_user_database(db)
return db
with open(USER_DB_PATH, 'r', encoding='utf-8') as file:
db = json.load(file)
# Ensure 'users' key exists
if 'users' not in db:
db['users'] = {}
for user_id in db.get('users', {}):
profile = db['users'][user_id]
if 'chat_history' not in profile or not isinstance(profile['chat_history'], list): profile['chat_history'] = []
else:
fixed_history = []
for msg in profile['chat_history']:
# Increased robustness of validation
if isinstance(msg, dict) and 'role' in msg:
role = msg['role']
if role in ['user', 'assistant', 'system']:
content = msg.get('content')
tool_calls = msg.get('tool_calls')
# Validate content type (string or None for assistant)
if not isinstance(content, (str, type(None))):
logger.warning(f"Skipping message with invalid content type for role {role} user {user_id}: {content}")
continue
# Validate tool_calls structure if present
if tool_calls is not None:
if not isinstance(tool_calls, list) or not all(isinstance(tc, dict) and 'id' in tc and 'type' in tc and 'function' in tc for tc in tool_calls):
logger.warning(f"Skipping message with invalid tool_calls structure for user {user_id}: {tool_calls}")
continue
# Check consistency: assistant needs content or tool_calls
if role == 'assistant' and content is None and tool_calls is None:
logger.warning(f"Skipping assistant message with no content and no tool_calls for user {user_id}")
continue
fixed_history.append(msg)
elif role == 'tool':
if 'tool_call_id' in msg and 'content' in msg and isinstance(msg.get('content'), str):
fixed_history.append(msg)
else:
logger.warning(f"Skipping invalid tool message structure for user {user_id}: {msg}")
# Allow system messages even if content is None (though unlikely)
elif role == 'system' and isinstance(msg.get('content'), (str, type(None))):
fixed_history.append(msg)
else:
logger.warning(f"Skipping message with invalid role/content combination for user {user_id}: {msg}")
else:
logger.warning(f"Skipping unrecognized message structure for user {user_id}: {msg}")
profile['chat_history'] = fixed_history
# Ensure other lists/fields exist with defaults
default_lists = ['recommendations', 'daily_emotions', 'completed_tasks', 'routine_history', 'strengths', 'areas_for_development', 'values']
default_strings = ['name', 'location', 'current_emotion', 'career_goal', 'industry', 'preferred_work_style', 'long_term_aspirations', 'resume_path', 'portfolio_path']
default_numbers = {'progress_points': 0}
default_other = {'experience_level': "Not specified"}
for key in default_lists:
if key not in profile or not isinstance(profile.get(key), list): profile[key] = []
for key in default_strings:
if key not in profile or not isinstance(profile.get(key), str): profile[key] = "" # Ensure string type
for key, default_value in default_numbers.items():
if key not in profile or not isinstance(profile.get(key), (int, float)): profile[key] = default_value
for key, default_value in default_other.items():
if key not in profile: profile[key] = default_value
return db
except json.JSONDecodeError as e:
logger.error(f"Error decoding JSON from {USER_DB_PATH}: {e}. Creating new DB.")
db = {'users': {}}
save_user_database(db)
return db
except Exception as e:
logger.error(f"Unexpected error loading DB from {USER_DB_PATH}: {e}. Returning empty DB.")
# Avoid saving over potentially recoverable data in case of unexpected errors
return {'users': {}}
def save_user_database(db):
# (Identical to v4)
try:
with open(USER_DB_PATH, 'w', encoding='utf-8') as file: json.dump(db, file, indent=4, ensure_ascii=False)
except Exception as e: logger.error(f"Error saving DB to {USER_DB_PATH}: {e}")
def get_user_profile(user_id):
# (Identical to v4)
db = load_user_database()
if user_id not in db.get('users', {}):
db['users'] = db.get('users', {})
# Initialize enhanced profile structure
db['users'][user_id] = {
"user_id": user_id, "name": "", "location": "", "industry": "",
"experience_level": "Not specified", "preferred_work_style": "Any",
"values": [], "strengths": [], "areas_for_development": [],
"long_term_aspirations": "", "current_emotion": "", "career_goal": "",
"progress_points": 0, "completed_tasks": [], "upcoming_events": [],
"routine_history": [], "daily_emotions": [], "resume_path": "",
"portfolio_path": "", "recommendations": [],
"chat_history": [], # Stores history in OpenAI/Groq compatible format
"joined_date": datetime.now().isoformat()
}
save_user_database(db)
# Re-ensure critical lists exist after potential creation or loading issues
profile = db.get('users', {}).get(user_id, {}) # Get potentially newly created profile
if 'chat_history' not in profile or not isinstance(profile.get('chat_history'), list):
profile['chat_history'] = []
for key in ['recommendations', 'daily_emotions', 'completed_tasks', 'routine_history', 'strengths', 'areas_for_development', 'values']:
if key not in profile or not isinstance(profile.get(key), list):
profile[key] = []
# Ensure essential string fields exist if somehow missed
for key in ['name', 'location', 'current_emotion', 'career_goal', 'industry', 'preferred_work_style', 'long_term_aspirations', 'resume_path', 'portfolio_path']:
if key not in profile:
profile[key] = ""
return profile
# --- Database Update Functions (Identical to v4) ---
def update_user_profile(user_id, updates):
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
for key, value in updates.items(): profile[key] = value
save_user_database(db); return profile
else: logger.warning(f"Attempted update non-existent profile: {user_id}"); return None
def add_task_to_user(user_id, task):
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'completed_tasks' not in profile or not isinstance(profile['completed_tasks'], list): profile['completed_tasks'] = []
task_with_date = { "task": task, "date": datetime.now().isoformat(), "points": random.randint(10, 25) }
profile['completed_tasks'].append(task_with_date); profile['progress_points'] = profile.get('progress_points', 0) + task_with_date["points"]
save_user_database(db); return profile
return None
def add_emotion_record(user_id, emotion):
cleaned_emotion = emotion.split(" ")[0] if " " in emotion else emotion
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'daily_emotions' not in profile or not isinstance(profile['daily_emotions'], list): profile['daily_emotions'] = []
emotion_record = { "emotion": cleaned_emotion, "date": datetime.now().isoformat() }
profile['daily_emotions'].append(emotion_record); profile['current_emotion'] = cleaned_emotion
save_user_database(db); return profile
return None
def add_routine_to_user(user_id, routine):
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'routine_history' not in profile or not isinstance(profile['routine_history'], list): profile['routine_history'] = []
try: days_delta = int(routine.get('days', 7))
except (ValueError, TypeError): days_delta = 7 # Handle non-integer values
end_date = (datetime.now() + timedelta(days=days_delta)).isoformat()
routine_with_date = { "routine": routine, "start_date": datetime.now().isoformat(), "end_date": end_date, "completion": 0 }
profile['routine_history'].insert(0, routine_with_date); profile['routine_history'] = profile['routine_history'][:10]
save_user_database(db); return profile
return None
def save_user_resume(user_id, resume_text):
if not resume_text: return None
filename, filepath = f"{user_id}_resume.txt", os.path.join(RESUME_FOLDER, f"{user_id}_resume.txt")
try:
with open(filepath, 'w', encoding='utf-8') as file: file.write(resume_text)
update_user_profile(user_id, {"resume_path": filepath}); logger.info(f"Resume saved: {filepath}"); return filepath
except Exception as e: logger.error(f"Error saving resume {filepath}: {e}"); return None
def save_user_portfolio(user_id, portfolio_url, portfolio_description):
if not portfolio_description: return None
filename, filepath = f"{user_id}_portfolio.json", os.path.join(PORTFOLIO_FOLDER, f"{user_id}_portfolio.json")
portfolio_content = {"url": portfolio_url, "description": portfolio_description, "saved_date": datetime.now().isoformat()}
try:
with open(filepath, 'w', encoding='utf-8') as file: json.dump(portfolio_content, file, indent=4, ensure_ascii=False)
update_user_profile(user_id, {"portfolio_path": filepath}); logger.info(f"Portfolio saved: {filepath}"); return filepath
except Exception as e: logger.error(f"Error saving portfolio {filepath}: {e}"); return None
def add_recommendation_to_user(user_id, recommendation):
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'recommendations' not in profile or not isinstance(profile['recommendations'], list): profile['recommendations'] = []
recommendation_with_date = {"recommendation": recommendation, "date": datetime.now().isoformat(), "status": "pending"}
profile['recommendations'].insert(0, recommendation_with_date); profile['recommendations'] = profile['recommendations'][:20]
save_user_database(db); return profile
return None
def add_chat_message(user_id, role, message_content):
# (Identical to v4 - handles OpenAI/Groq compatible format)
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if not profile: logger.warning(f"Profile not found for {user_id} when adding chat message."); return None
if 'chat_history' not in profile or not isinstance(profile['chat_history'], list): profile['chat_history'] = []
if role not in ['user', 'assistant', 'system', 'tool']: logger.warning(f"Invalid role '{role}' for chat history."); return profile
message = {"role": role}
if role == 'user' or role == 'system':
if isinstance(message_content, str): message['content'] = message_content
else: logger.warning(f"Invalid content type for role {role}: {type(message_content)}."); return profile
elif role == 'assistant':
if isinstance(message_content, dict):
message['content'] = message_content.get('content')
if 'tool_calls' in message_content:
if isinstance(message_content['tool_calls'], list) and all(isinstance(tc, dict) and 'id' in tc and 'type' in tc and 'function' in tc for tc in message_content['tool_calls']): message['tool_calls'] = message_content['tool_calls']
else: logger.warning(f"Invalid tool_calls structure: {message_content.get('tool_calls')}")
if not isinstance(message['content'], (str, type(None))): logger.warning(f"Invalid content type: {type(message['content'])}"); message['content'] = str(message['content'])
elif isinstance(message_content, str): message['content'] = message_content
else: logger.warning(f"Invalid content type for role {role}: {type(message_content)}."); return profile
elif role == 'tool':
if isinstance(message_content, dict) and 'tool_call_id' in message_content and 'content' in message_content:
message['tool_call_id'] = message_content['tool_call_id']
if isinstance(message_content['content'], str): message['content'] = message_content['content']
else:
try: message['content'] = json.dumps(message_content['content'])
except Exception as e: logger.error(f"Could not stringify tool content: {e}"); message['content'] = json.dumps({"error": "Failed to serialize tool result."})
else: logger.warning(f"Invalid content format for role {role}: {message_content}."); return profile
profile['chat_history'].append(message)
max_history_turns = 25
if len(profile['chat_history']) > max_history_turns * 2:
first_non_system = 0
if profile['chat_history'] and profile['chat_history'][0]['role'] == 'system': first_non_system = 1
profile['chat_history'] = profile['chat_history'][:first_non_system] + profile['chat_history'][-(max_history_turns * 2):]
save_user_database(db); return profile
# --- Basic Routine Fallback Function (Identical to v4) ---
def generate_basic_routine(emotion, goal, available_time=60, days=7):
# (Code identical to the provided v3/v4 version)
logger.info(f"Generating basic fallback routine for emotion={emotion}, goal={goal}")
routine_types = { "job_search": [ {"name": "Research Target Companies", "points": 15, "duration": 20, "description": "Identify 3 potential employers aligned with your goal."}, {"name": "Update LinkedIn Section", "points": 15, "duration": 25, "description": "Refine one section of your LinkedIn profile (e.g., summary, experience)."}, {"name": "Practice STAR Method", "points": 20, "duration": 15, "description": "Outline one experience using the STAR method for interviews."}, {"name": "Find Networking Event", "points": 10, "duration": 10, "description": "Look for one relevant online or local networking event."} ], "skill_building": [ {"name": "Online Tutorial (1 Module)", "points": 25, "duration": 45, "description": "Complete one module of a relevant online course/tutorial."}, {"name": "Read Industry Blog/Article", "points": 10, "duration": 15, "description": "Read and summarize one article about trends in your field."}, {"name": "Small Project Task", "points": 30, "duration": 60, "description": "Dedicate time to a specific task within a personal project."}, {"name": "Review Skill Documentation", "points": 15, "duration": 30, "description": "Read documentation or examples for a skill you're learning."} ], "motivation_wellbeing": [ {"name": "Mindful Reflection", "points": 10, "duration": 10, "description": "Spend 10 minutes reflecting on progress and challenges without judgment."}, {"name": "Set 1-3 Daily Intentions", "points": 10, "duration": 5, "description": "Define small, achievable goals for the day."}, {"name": "Short Break/Walk", "points": 15, "duration": 15, "description": "Take a brief break away from screens, preferably with light movement."}, {"name": "Connect with Support", "points": 20, "duration": 20, "description": "Briefly chat with a friend, mentor, or peer about your journey."} ] }
cleaned_emotion = emotion.split(" ")[0].lower() if " " in emotion else emotion.lower(); negative_emotions = ["unmotivated", "anxious", "confused", "overwhelmed", "discouraged", "stuck"]
# ** FIX Syntax Error Here **
base_type = "skill_building" # Default
if any(term in goal.lower() for term in ["job", "internship", "company", "freelance", "contract"]):
base_type = "job_search"
elif any(term in goal.lower() for term in ["skill", "learn", "development"]):
base_type = "skill_building"
elif "network" in goal.lower():
base_type = "job_search"
# The 'else' was incorrectly placed on the same line as the elif above.
include_wellbeing = cleaned_emotion in negative_emotions or "overwhelmed" in cleaned_emotion; daily_tasks_list = []
for day in range(1, days + 1):
day_tasks, remaining_time, tasks_added_count = [], available_time, 0; possible_tasks = routine_types[base_type].copy()
if include_wellbeing: possible_tasks.extend(routine_types["motivation_wellbeing"]); random.shuffle(possible_tasks)
for task in possible_tasks:
if task.get("duration", 0) > 0 and task["duration"] <= remaining_time and tasks_added_count < 3: day_tasks.append(task); remaining_time -= task["duration"]; tasks_added_count += 1
if remaining_time < 10 or tasks_added_count >= 3: break
daily_tasks_list.append({"day": day, "tasks": day_tasks})
routine = {"name": f"{days}-Day Focus Plan", "description": f"A focused {days}-day plan to help you with '{goal}', especially while feeling {cleaned_emotion}. We'll do this step-by-step!", "days": days, "daily_tasks": daily_tasks_list, "support_message": f"Hey, I know feeling {cleaned_emotion} while aiming for '{goal}' can be tough. We've got this routine to help break it down. One step at a time, okay? You're doing great just by planning!"}
return routine
# --- Tool Implementation Functions (Return JSON strings - Identical to v4) ---
def generate_document_template(document_type: str, career_field: str = "", experience_level: str = "") -> str:
logger.info(f"Executing tool: generate_document_template(type='{document_type}', field='{career_field}', exp='{experience_level}')")
template = f"## Basic Template: {document_type}\n\n**Target Field:** {career_field or 'Not specified'}\n**Experience Level:** {experience_level or 'Not specified'}\n\n---\n\n"
if "resume" in document_type.lower(): template += """### Contact Information\n* Name:\n* Phone:\n* Email:\n* LinkedIn URL:\n* Portfolio URL (Optional):\n\n### Summary/Objective\n* _[ 2-3 sentences summarizing your key skills, experience, and career goals, tailored to the job/field. Make it impactful! ]_\n\n### Experience\n**Company Name | Location | Job Title | Start Date – End Date**\n* Accomplishment 1 (Use action verbs: Led, Managed, Developed, Increased X by Y%. Quantify results!)\n* Accomplishment 2\n* _[ Repeat for other relevant positions ]_\n\n### Education\n**University/Institution Name | Degree | Graduation Date (or Expected)**\n* Relevant coursework, honors, activities (Optional)\n\n### Skills\n* **Technical Skills:** [ e.g., Python, Java, SQL, MS Excel, Google Analytics, Figma, AWS ]\n* **Languages:** [ e.g., English (Native), Spanish (Fluent) ]\n* **Other:** [ Certifications, relevant tools, methodologies like Agile/Scrum ]\n"""
elif "cover letter" in document_type.lower(): template += """[Your Name]\n[Your Address]\n[Your Phone]\n[Your Email]\n\n[Date]\n\n[Hiring Manager Name (if known), or 'Hiring Team']\n[Hiring Manager Title (if known)]\n[Company Name]\n[Company Address]\n\n**Subject: Application for [Job Title] Position - [Your Name]**\n\nDear [Mr./Ms./Mx. Last Name or Hiring Team],\n\n**Introduction:** State the position you're applying for and where you saw it. Express genuine enthusiasm for the role *and* the company. Briefly highlight 1-2 key qualifications that make you a perfect fit right from the start.\n* _[ Example: I am writing to express my strong interest in the [Job Title] position advertised on [Platform]. With my background in [Relevant Field] and proven ability to [Key Skill Relevant to Job], I am confident I can bring significant value to [Company Name]'s mission in [Specific Area Company Works In]. ]_\n\n**Body Paragraph(s):** This is where you connect your experience to the job description. Don't just list duties; show *impact*. Use examples (think STAR method: Situation, Task, Action, Result). Explain *why* you're drawn to *this specific company* – mention their values, projects, or recent news. Show you've done your homework!\n* _[ Example: In my previous role at [Previous Company], I spearheaded a project that [Quantifiable achievement relevant to new job], demonstrating my expertise in [Skill required by new job]. I admire [Company Name]'s innovative approach to [Specific Company Initiative], and I believe my skills in [Another Relevant Skill] align perfectly with the requirements of this role and your company culture. ]_\n\n**Conclusion:** Reiterate your strong interest and suitability. Briefly summarize your key selling points. State your call to action confidently (e.g., "I am eager to discuss how my skills can benefit [Company Name]..."). Thank the reader for their time and consideration.\n* _[ Example: Thank you for considering my application. My attached resume provides further detail on my qualifications. I am excited about the potential to contribute to your team and look forward to hearing from you soon regarding an interview. ]_\n\nSincerely,\n\n[Your Typed Name]\n"""
elif "linkedin summary" in document_type.lower(): template += """### LinkedIn Summary / About Section Template\n\n**Headline:** [ Make this keyword-rich and concise! Who are you professionally? What's your focus? e.g., 'Software Engineer specializing in AI & Cloud | Python | Ex-Google | Building Innovative Solutions' OR 'Marketing Manager | Driving Growth for SaaS Startups | Content Strategy & Demand Generation' ]\n\n**About Section:**\n\n* **[ Paragraph 1: Hook & Overview ]** Start with a compelling statement about your passion, mission, or core expertise. Who are you, what do you do, and what drives you? Use keywords relevant to your target roles/industry. Think of this as your elevator pitch.\n* **[ Paragraph 2: Key Skills & Experience Highlights ]** Detail your core competencies, both technical and soft skills. Mention significant experiences, types of projects, or industries you've worked in. Quantify achievements whenever possible (e.g., 'Managed budgets up to $X', 'Increased user engagement by Y%'). Tailor this to attract your desired audience (recruiters, clients, collaborators).\n* **[ Paragraph 3: Career Goals & What You're Seeking (Optional but Recommended) ]** Briefly state your current career aspirations. What kind of opportunities, connections, or challenges are you looking for? Be specific if possible (e.g., 'Seeking opportunities in AI ethics', 'Open to collaborating on open-source projects').\n* **[ Paragraph 4: Call to Action / Personality (Optional) ]** You might invite relevant connections, mention personal interests related to your field, or add a touch of personality to make you more memorable. What makes you, you?\n* **[ Specialties/Keywords: ]** _[ List 5-15 key terms separated by commas or bullet points that recruiters might search for. e.g., Project Management, Data Analysis, Agile Methodologies, Content Strategy, Python, Java, Cloud Security, UX/UI Design, B2B Marketing ]_\n"""
else: template += "[ Template structure for this document type will be provided here. Let me know what you need! ]"
return json.dumps({"template_markdown": template})
def create_personalized_routine(emotion: str, goal: str, available_time_minutes: int = 60, routine_length_days: int = 7) -> str:
logger.info(f"Executing tool: create_personalized_routine(emo='{emotion}', goal='{goal}', time={available_time_minutes}, days={routine_length_days})")
logger.warning("Using basic fallback for create_personalized_routine for robustness.")
try:
routine_dict = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days)
if not routine_dict or not isinstance(routine_dict, dict): raise ValueError("Basic routine generation failed.")
return json.dumps(routine_dict)
except Exception as e: logger.error(f"Error in create_personalized_routine fallback: {e}"); return json.dumps({"error": f"Couldn't create routine: {e}."})
def analyze_resume(resume_text: str, career_goal: str) -> str:
logger.info(f"Executing tool: analyze_resume(goal='{career_goal}', len={len(resume_text)})"); logger.warning("Using placeholder analysis for analyze_resume tool.")
analysis = { "strengths": ["Clear contact info.", "Uses action verbs.", f"Mentions skills relevant to '{career_goal}'."], "areas_for_improvement": ["Quantify achievements.", f"Tailor skills section for '{career_goal}'.", "Check formatting consistency.", "Add compelling summary."], "format_feedback": "Clean format, check consistency.", "content_feedback": f"Potentially relevant to '{career_goal}', needs more specific examples/results.", "keyword_suggestions": ["Review job descriptions for "+ career_goal +" and add keywords like 'Keyword1', 'Keyword2'."], "next_steps": ["Revise 'Experience' bullets with measurable results.", "Tailor Summary/Skills per application.", "Proofread."] }
return json.dumps({"analysis": analysis})
def analyze_portfolio(portfolio_description: str, career_goal: str, portfolio_url: str = "") -> str:
logger.info(f"Executing tool: analyze_portfolio(goal='{career_goal}', url='{portfolio_url}', desc_len={len(portfolio_description)})"); logger.warning("Using placeholder analysis for analyze_portfolio tool.")
analysis = { "alignment_with_goal": f"Moderately aligned with '{career_goal}'. Review projects.", "strengths": ["Project variety.", "Clear description."] + (["URL provided."] if portfolio_url else []), "areas_for_improvement": [f"Link project skills to '{career_goal}'.", "Add case studies.", "Check navigation (if URL)."], "presentation_feedback": "Description helpful. " + (f"Review URL ({portfolio_url}) for appeal/clarity." if portfolio_url else "Consider creating online portfolio."), "next_steps": ["Highlight 2-3 relevant projects.", "Get peer feedback.", "Ensure contact info accessible."] }
return json.dumps({"analysis": analysis})
def extract_and_rate_skills_from_resume(resume_text: str, max_skills: int = 8) -> str:
logger.info(f"Executing tool: extract_skills(len={len(resume_text)}, max={max_skills})"); logger.warning("Using placeholder skill extraction.")
possible = ["Python", "Java", "JavaScript", "Project Management", "Communication", "Data Analysis", "Teamwork", "Leadership", "SQL", "React", "Customer Service", "Problem Solving", "Cloud Computing", "AWS", "Azure", "GCP", "Agile Methodologies", "Machine Learning", "Marketing", "SEO", "Content Creation"]
found = []; resume_lower = resume_text.lower()
for skill in possible:
if re.search(r'\b' + re.escape(skill.lower()) + r'\b', resume_lower):
score = random.randint(4, 9); found.append({"name": skill, "score": score})
if len(found) >= max_skills: break
if not found and len(resume_text) > 100: found = [ {"name": "Communication", "score": random.randint(5,8)}, {"name": "Teamwork", "score": random.randint(5,8)}, {"name": "Problem Solving", "score": random.randint(5,8)}, ]
logger.info(f"Extracted skills (placeholder): {[s['name'] for s in found]}")
return json.dumps({"skills": found[:max_skills]})
def search_web_serper(search_query: str, search_type: str = 'general', location: str = None) -> str:
# (Identical to v4)
logger.info(f"Executing tool: search_web_serper(query='{search_query}', type='{search_type}', loc='{location}')")
if not SERPER_API_KEY: logger.error("SERPER_API_KEY not configured."); return json.dumps({"error": "Web search functionality is not configured."})
api_url = "https://google.serper.dev/search"; payload = json.dumps({"q": search_query,"location": location if location else None}); headers = {'X-API-KEY': SERPER_API_KEY,'Content-Type': 'application/json'}
try:
response = requests.post(api_url, headers=headers, data=payload, timeout=10); response.raise_for_status(); results = response.json(); extracted_results = []
if search_type == 'jobs':
if 'jobs' in results:
for job in results['jobs'][:5]: extracted_results.append({"title": job.get('title'),"company": job.get('company_name'),"location": job.get('location'),"link": job.get('link')})
elif 'organic' in results:
for item in results['organic'][:5]:
if any(kw in item.get('title', '').lower() for kw in ['hiring', 'job', 'career', 'vacancy']): extracted_results.append({"title": item.get('title'),"snippet": item.get('snippet'),"link": item.get('link')})
elif search_type in ['courses', 'skills']:
if 'organic' in results:
for item in results['organic'][:5]: extracted_results.append({"title": item.get('title'),"snippet": item.get('snippet'),"link": item.get('link')})
else:
if 'organic' in results:
for item in results['organic'][:3]: extracted_results.append({"title": item.get('title'),"snippet": item.get('snippet'),"link": item.get('link')})
if 'answerBox' in results: extracted_results.insert(0, {"type": "Answer Box","title": results['answerBox'].get('title'),"snippet": results['answerBox'].get('snippet') or results['answerBox'].get('answer'),"link": results['answerBox'].get('link')})
logger.info(f"Serper search successful for '{search_query}'. Found {len(extracted_results)} relevant items.")
return json.dumps({"search_results": extracted_results})
except requests.exceptions.RequestException as e: logger.error(f"Serper API request failed: {e}"); return json.dumps({"error": f"Web search failed: {e}"})
except Exception as e: logger.error(f"Error processing Serper response: {e}"); return json.dumps({"error": "Failed to process web search results."})
# --- AI Interaction Logic (Using Groq Llama 3 with Streaming) ---
def get_ai_response_stream(user_id: str, user_input: str) -> Generator[str, None, None]:
"""
Gets response from Groq, handling context, system prompt, tool calls,
and streams the final text response.
Yields chunks of the response text.
"""
logger.info(f"Getting Groq stream response for user {user_id}. Input: '{user_input[:100]}...'")
if not client:
logger.error("Groq client not initialized.")
yield "I'm sorry, my AI core isn't available right now. Please check the configuration."
return
try:
user_profile = get_user_profile(user_id)
if not user_profile:
logger.error(f"Failed profile retrieval for {user_id}.")
yield "Uh oh, I couldn't access your profile details right now. Let's try again in a moment?"
return
# System prompt (identical persona to v4)
current_emotion_display = user_profile.get('current_emotion', 'how you feel'); user_name = user_profile.get('name', 'there'); career_goal = user_profile.get('career_goal', 'your goals'); location = user_profile.get('location', 'your area'); industry = user_profile.get('industry', 'your field'); exp_level = user_profile.get('experience_level', 'your experience level')
# ** Updated System Prompt Model Name **
system_prompt = f"""You are Aishura, an advanced AI career assistant powered by Groq's {MODEL_ID} model. Your core mission is to provide **empathetic, supportive, and highly personalized career guidance**. You are talking to {user_name}. **Persona & Style:** Empathetic, validating (acknowledge {current_emotion_display}), collaborative ("we", "us"), positive, action-oriented, personalized (use {user_name}, {career_goal}, {location}, {industry}, {exp_level}), concise, clear (markdown). **Functionality:** 1. Acknowledge & Empathize. 2. Address Query Directly. 3. Leverage Tools Strategically: Suggest `generate_document_template`, `create_personalized_routine`, `analyze_resume`, `analyze_portfolio`, `extract_and_rate_skills_from_resume` proactively. Use `search_jobs_courses_skills` ONLY when explicitly asked for jobs/courses/skills/company info (use profile details for query, specify type, present results clearly). Do NOT use tools for general chat. 4. Synthesize Tool Results: Explain relevance. 5. Maintain Context. 6. Handle Errors Gracefully: Apologize simply, suggest alternatives."""
# Prepare message history (OpenAI/Groq compatible format)
messages = [{"role": "system", "content": system_prompt}]
chat_history = user_profile.get('chat_history', [])
for msg in chat_history:
# Append validated messages from history (using logic from load_user_database)
if isinstance(msg, dict) and 'role' in msg:
api_msg = {"role": msg["role"]}
if msg["role"] in ["user", "assistant", "system"]:
if 'content' in msg and isinstance(msg.get('content'), (str, type(None))): api_msg['content'] = msg.get('content')
else:
if msg["role"] != 'assistant': continue
else: api_msg['content'] = None
if msg["role"] == 'assistant' and 'tool_calls' in msg and isinstance(msg['tool_calls'], list):
valid_tool_calls = all(isinstance(tc, dict) and 'id' in tc and 'type' in tc and 'function' in tc for tc in msg['tool_calls'])
if valid_tool_calls: api_msg['tool_calls'] = msg['tool_calls']
else:
if api_msg['content'] is None: continue
# Ensure content is not None OR tool_calls are present before appending
if api_msg.get('content') is not None or api_msg.get('tool_calls'):
messages.append(api_msg)
elif msg["role"] == "tool":
if 'tool_call_id' in msg and 'content' in msg and isinstance(msg.get('content'), str):
api_msg['tool_call_id'] = msg['tool_call_id']; api_msg['content'] = msg['content']; messages.append(api_msg)
else: continue
else: continue
else: continue
# Add current user input
messages.append({"role": "user", "content": user_input})
# --- Make the initial API Call ---
logger.info(f"Sending {len(messages)} messages to Groq model {MODEL_ID}.")
try:
response = client.chat.completions.create(
model=MODEL_ID,
messages=messages,
tools=tools_list_groq,
tool_choice="auto",
temperature=0.7, # Adjust temperature as needed
max_tokens=1500, # Max tokens for the completion
top_p=1,
stream=False # First call is not streamed to check for tool calls
)
response_message = response.choices[0].message
finish_reason = response.choices[0].finish_reason
# --- Handle Groq API Errors ---
except APIError as e:
# ** Specific check for model decommission error **
if e.status_code == 400 and 'model_decommissioned' in str(e.body):
logger.error(f"Groq API Error: Model '{MODEL_ID}' is decommissioned. {e.body}")
yield f"AI service error: The model '{MODEL_ID}' is no longer available. Please update the application."
return
else:
logger.error(f"Groq API Error: {e.status_code} - {e.response}"); yield f"AI service error ({e.message}). Try again." ; return
except APITimeoutError: logger.error("Groq timed out."); yield "AI service request timed out. Try again."; return
except APIConnectionError as e: logger.error(f"Groq Connection Error: {e}"); yield "Cannot connect to AI service."; return
except RateLimitError: logger.error("Groq Rate Limit Exceeded."); yield "AI service busy (Rate Limit). Try again shortly."; return
except AuthenticationError: logger.error("Groq Authentication Error. Check API Key."); yield "AI Authentication failed. Please check configuration."; return
except Exception as e: logger.exception(f"Unexpected error during Groq API call: {e}"); yield "Oh dear, something unexpected happened on my end. Let's pause and retry?"; return
# --- Process the response ---
tool_calls = response_message.tool_calls
# Store user message
add_chat_message(user_id, "user", user_input)
# Store the initial assistant message (might contain text and/or tool calls)
assistant_message_for_db = {"content": response_message.content}
if tool_calls:
# Ensure tool_calls are serializable (they should be from Groq client)
try:
assistant_message_for_db['tool_calls'] = [tc.model_dump() for tc in tool_calls]
except Exception as dump_err:
logger.error(f"Error serializing tool calls: {dump_err}")
# Handle error - maybe store without tool calls or with an error placeholder
assistant_message_for_db['tool_calls'] = [{"error": "Failed to serialize tool call"}]
add_chat_message(user_id, "assistant", assistant_message_for_db)
# --- Handle Tool Calls if any ---
if tool_calls:
logger.info(f"Groq requested tool call(s): {[tc.function.name for tc in tool_calls]}")
messages.append(response_message) # Add assistant's msg with tool_calls
available_functions = { "generate_document_template": generate_document_template, "create_personalized_routine": create_personalized_routine, "analyze_resume": analyze_resume, "analyze_portfolio": analyze_portfolio, "extract_and_rate_skills_from_resume": extract_and_rate_skills_from_resume, "search_jobs_courses_skills": search_web_serper, }
# Execute functions and gather results
tool_results_for_api = [] # Store results to send back to the model
for tool_call in tool_calls:
function_name = tool_call.function.name; function_to_call = available_functions.get(function_name); tool_call_id = tool_call.id; function_response_content = None
try:
function_args = json.loads(tool_call.function.arguments)
if function_to_call:
# Special handling before calling (same as v4)
if function_name == "analyze_resume":
if 'career_goal' not in function_args: function_args['career_goal'] = career_goal
save_user_resume(user_id, function_args.get('resume_text', ''))
elif function_name == "analyze_portfolio":
if 'career_goal' not in function_args: function_args['career_goal'] = career_goal
save_user_portfolio(user_id, function_args.get('portfolio_url', ''), function_args.get('portfolio_description', ''))
elif function_name == "search_jobs_courses_skills":
if 'location' not in function_args or not function_args['location']: function_args['location'] = location if location != 'your area' else None
logger.info(f"Calling function '{function_name}' with args: {function_args}")
function_response_content = function_to_call(**function_args) # Expecting JSON string
logger.info(f"Function '{function_name}' returned: {function_response_content[:200]}...")
else: logger.warning(f"Function {function_name} not implemented."); function_response_content = json.dumps({"error": f"Tool '{function_name}' not available."})
except json.JSONDecodeError as e: logger.error(f"Error decoding args for {function_name}: {tool_call.function.arguments} - {e}"); function_response_content = json.dumps({"error": f"Invalid arguments for tool '{function_name}'."})
except TypeError as e: logger.error(f"Argument mismatch for {function_name}. Args: {function_args}, Error: {e}"); function_response_content = json.dumps({"error": f"Internal error: Tool '{function_name}' called incorrectly."})
except Exception as e: logger.exception(f"Error executing function {function_name}: {e}"); function_response_content = json.dumps({"error": f"Error using the '{function_name}' tool."})
# Append result for the next API call
tool_results_for_api.append({
"tool_call_id": tool_call_id,
"role": "tool",
"content": function_response_content,
})
# Also store in DB history
add_chat_message(user_id, "tool", {"tool_call_id": tool_call_id, "content": function_response_content})
messages.extend(tool_results_for_api) # Add all tool results to messages
# --- Make the second API Call (Streaming this time) ---
logger.info(f"Sending {len(messages)} messages to Groq (incl. tool results) for streaming response.")
try:
stream = client.chat.completions.create(
model=MODEL_ID,
messages=messages,
temperature=0.7,
max_tokens=1500,
top_p=1,
stream=True, # Enable streaming
)
# Yield chunks and accumulate the full response for DB
full_response_content = ""
for chunk in stream:
delta_content = chunk.choices[0].delta.content
if delta_content:
yield delta_content # Yield the text chunk to the caller (Gradio)
full_response_content += delta_content
# Handle potential finish reason if needed
if chunk.choices[0].finish_reason:
logger.info(f"Streaming (after tool call) finished with reason: {chunk.choices[0].finish_reason}")
logger.info("Finished streaming final response after tool calls.")
# Store the complete final assistant response in DB
add_chat_message(user_id, "assistant", {"content": full_response_content})
return # End the generator
# --- Handle Groq API Errors for the streaming call ---
except APIError as e: logger.error(f"Groq API Error (stream): {e.status_code} - {e.response}"); yield f"AI service error ({e.message}) processing tool results." ; return
except RateLimitError: logger.error("Groq Rate Limit Exceeded (stream)."); yield "AI service busy processing results. Try again shortly."; return
except Exception as e: logger.exception(f"Unexpected error during Groq stream: {e}"); yield "Oh dear, something went wrong while generating the response."; return
else: # No tool calls were made, stream the initial response
logger.info("No tool calls requested by Groq. Streaming initial response.")
# Need to make the call again with stream=True
try:
# We already have the user message in 'messages', just need to call stream
stream = client.chat.completions.create(
model=MODEL_ID,
messages=messages, # History includes system + previous + user
temperature=0.7,
max_tokens=1500,
top_p=1,
stream=True,
)
# Yield chunks and accumulate full response for DB update
full_response_content = ""
first_chunk = True
for chunk in stream:
delta_content = chunk.choices[0].delta.content
if delta_content:
yield delta_content
full_response_content += delta_content
# Handle potential finish reason if needed (e.g., length limit)
if chunk.choices[0].finish_reason:
logger.info(f"Streaming finished with reason: {chunk.choices[0].finish_reason}")
logger.info("Finished streaming initial response.")
# Update the assistant message stored earlier ONLY if it was a placeholder
# A better way: store the full message *after* streaming is complete.
db = load_user_database()
profile = db.get('users', {}).get(user_id)
if profile and profile['chat_history'] and profile['chat_history'][-1]['role'] == 'assistant':
# Check if the stored message was the one corresponding to this stream
# This check is imperfect without unique IDs per message turn.
# Assuming the last assistant message is the one to update.
profile['chat_history'][-1]['content'] = full_response_content
# Clear potential placeholder tool calls if no real ones occurred
profile['chat_history'][-1].pop('tool_calls', None)
save_user_database(db) # Save the updated history
else:
# Fallback: Add as a new message if history seems inconsistent
logger.warning("Could not reliably update last assistant message, adding new one.")
add_chat_message(user_id, "assistant", {"content": full_response_content})
return # End the generator
# --- Handle Groq API Errors for the streaming call ---
except APIError as e: logger.error(f"Groq API Error (stream): {e.status_code} - {e.response}"); yield f"AI service error ({e.message})." ; return
except RateLimitError: logger.error("Groq Rate Limit Exceeded (stream)."); yield "AI service busy. Try again shortly."; return
except Exception as e: logger.exception(f"Unexpected error during Groq stream: {e}"); yield "Oh dear, something went wrong generating the response."; return
except Exception as e:
logger.exception(f"Critical error in get_ai_response_stream: {e}")
yield "A critical error occurred. Please try again later."
return
# --- Recommendation Generation (Simple version - unchanged) ---
def gen_recommendations_simple(user_id):
# (Identical to v4)
logger.info(f"Generating simple recommendations for user {user_id}")
profile = get_user_profile(user_id); recs = []; goal = profile.get('career_goal', '').lower(); emotion = profile.get('current_emotion', '').lower()
if 'job' in goal or 'internship' in goal: recs.append({"title": "Refine Resume", "description": f"Tailor resume for '{goal}'.", "priority": "High", "action_type": "Job Application"}); recs.append({"title": "Practice Interviewing", "description": "Use STAR method.", "priority": "Medium", "action_type": "Skill Building"}); recs.append({"title": "Network Actively", "description": f"Connect in '{profile.get('industry', 'your')}' industry.", "priority": "Medium", "action_type": "Networking"})
if 'skill' in goal: recs.append({"title": "Identify Learning Resources", "description": f"Find courses/tutorials for '{goal}'.", "priority": "High", "action_type": "Skill Building"}); recs.append({"title": "Start a Small Project", "description": f"Apply skills in a project.", "priority": "Medium", "action_type": "Skill Building"})
if emotion in ["anxious", "overwhelmed", "stuck", "unmotivated", "discouraged"]: recs.append({"title": "Focus on Small Wins", "description": "Break tasks into small steps.", "priority": "High", "action_type": "Wellbeing"}); recs.append({"title": "Schedule Breaks", "description": "Take regular short breaks.", "priority": "Medium", "action_type": "Wellbeing"})
if recs:
current_recs = profile.get('recommendations', []); pending_titles = {r['recommendation'].get('title') for r in current_recs if r.get('status') == 'pending'}; new_recs_to_add = [r for r in recs if r.get('title') not in pending_titles]
for rec in new_recs_to_add[:3]: add_recommendation_to_user(user_id, rec)
return
# --- Chart and Visualization Functions (Identical to v4) ---
def create_emotion_chart(user_id):
user_profile = get_user_profile(user_id); records = user_profile.get('daily_emotions', [])
if not records: fig = go.Figure(); fig.add_annotation(text="No emotion data yet.", showarrow=False); fig.update_layout(title="Your Emotional Journey"); return fig
vals = {"Unmotivated": 1, "Discouraged": 1.5, "Stuck": 2, "Anxious": 2.5, "Confused": 3, "Overwhelmed": 3.5, "Hopeful": 4.5, "Focused": 5, "Excited": 6}
dates = [datetime.fromisoformat(r['date']) for r in records]; scores = [vals.get(r['emotion'], 3) for r in records]; names = [r['emotion'] for r in records]
df = pd.DataFrame({'Date': dates, 'Score': scores, 'Emotion': names}).sort_values('Date')
fig = px.line(df, x='Date', y='Score', markers=True, labels={"Score": "State"}, title="Your Emotional Journey"); fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}<br>Feeling: %{text}<extra></extra>', text=df['Emotion']); fig.update_yaxes(tickvals=list(vals.values()), ticktext=list(vals.keys())); return fig
def create_progress_chart(user_id):
user_profile = get_user_profile(user_id); tasks = user_profile.get('completed_tasks', [])
if not tasks: fig = go.Figure(); fig.add_annotation(text="No tasks completed yet.", showarrow=False); fig.update_layout(title="Progress Points"); return fig
tasks.sort(key=lambda x: datetime.fromisoformat(x['date'])); task_dates = {}
for task in tasks: task_date_str = datetime.fromisoformat(task['date']).strftime('%Y-%m-%d'); pts = task.get('points', 15); task_dates.setdefault(task_date_str, {'date': datetime.fromisoformat(task['date']).date(), 'points': 0, 'tasks': []}); task_dates[task_date_str]['points'] += pts; task_dates[task_date_str]['tasks'].append(task['task'])
sorted_dates = sorted(task_dates.keys()); cumulative_points = 0; chart_dates, chart_points, chart_tasks = [], [], []
for date_str in sorted_dates: day_data = task_dates[date_str]; cumulative_points += day_data['points']; chart_dates.append(day_data['date']); chart_points.append(cumulative_points); chart_tasks.append("<br>".join(day_data['tasks']))
if not chart_dates: fig = go.Figure(); fig.add_annotation(text="Error processing task data.", showarrow=False); fig.update_layout(title="Progress Points"); return fig
df = pd.DataFrame({'Date': chart_dates, 'Points': chart_points, 'Tasks': chart_tasks})
fig = px.line(df, x='Date', y='Points', markers=True, title="Progress Journey"); fig.update_traces(hovertemplate='%{x|%Y-%m-%d}<br>Points: %{y}<br>Tasks:<br>%{text}<extra></extra>', text=df['Tasks']); return fig
def create_routine_completion_gauge(user_id):
user_profile = get_user_profile(user_id); routines = user_profile.get('routine_history', [])
if not routines: fig = go.Figure(go.Indicator(mode="gauge", value=0, title={'text': "Active Routine"})); fig.add_annotation(text="No routine active.", showarrow=False); return fig
latest = routines[0]; completion = latest.get('completion', 0); name = latest.get('routine', {}).get('name', 'Routine')
fig = go.Figure(go.Indicator(mode="gauge+number", value=completion, domain={'x': [0, 1], 'y': [0, 1]}, title={'text': f"{name} (%)"}, gauge={'axis': {'range': [0, 100]}, 'bar': {'color': "cornflowerblue"}, 'bgcolor': "white", 'steps': [{'range': [0, 50], 'color': 'whitesmoke'}, {'range': [50, 80], 'color': 'lightgray'}], 'threshold': {'line': {'color': "green", 'width': 4}, 'thickness': 0.75, 'value': 90}})); return fig
def create_skill_radar_chart(user_id):
logger.info(f"Creating skill chart for {user_id}"); user_profile = get_user_profile(user_id); path = user_profile.get('resume_path')
if not path or not os.path.exists(path): logger.warning("No resume found for skill chart."); fig = go.Figure(); fig.add_annotation(text="Upload Resume for Skill Chart", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
try:
with open(path, 'r', encoding='utf-8') as f: text = f.read()
skills_json_str = extract_and_rate_skills_from_resume(resume_text=text); skills_data = json.loads(skills_json_str)
if 'skills' in skills_data and skills_data['skills']:
skills = skills_data['skills'][:8]; cats = [s['name'] for s in skills]; vals = [s['score'] for s in skills]
if len(cats) < 3: fig = go.Figure(); fig.add_annotation(text="Need >= 3 skills for radar.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
if len(cats) > 2: cats.append(cats[0]); vals.append(vals[0])
fig = go.Figure(); fig.add_trace(go.Scatterpolar(r=vals, theta=cats, fill='toself', name='Skills', hovertemplate='Skill: %{theta}<br>Score: %{r}<extra></extra>'))
fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 10], showline=False, ticksuffix=' pts')), showlegend=False, title="Skill Assessment (from Resume)")
logger.info(f"Created radar chart with {len(skills)} skills."); return fig
else: logger.warning("No skills extracted."); fig = go.Figure(); fig.add_annotation(text="No skills extracted yet.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
except Exception as e: logger.exception(f"Error creating skill chart: {e}"); fig = go.Figure(); fig.add_annotation(text="Error analyzing skills.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
# --- Gradio Interface Components (Adapting Chat for Streaming) ---
def create_interface():
"""Create the Gradio interface for Aishura v5 (Groq Streaming)"""
session_user_id = str(uuid.uuid4())
logger.info(f"Initializing Gradio interface v5 for session user ID: {session_user_id}")
get_user_profile(session_user_id) # Initialize profile
# --- Event Handlers ---
def welcome(name, location, emotion, goal, industry, exp_level, work_style):
# (Logic mostly identical to v4, but calls streaming AI function)
logger.info(f"Welcome v5: name='{name}', loc='{location}', emo='{emotion}', goal='{goal}', industry='{industry}', exp='{exp_level}', work='{work_style}'")
if not all([name, location, emotion, goal]): return ("Fill Name, Location, Emotion, Goal!", gr.update(visible=True), gr.update(visible=False), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())
cleaned_goal = goal.rsplit(" ", 1)[0] if goal[-1].isnumeric() == False and goal[-2] == " " else goal
profile_updates = {"name": name, "location": location, "career_goal": cleaned_goal, "industry": industry, "experience_level": exp_level, "preferred_work_style": work_style}
update_user_profile(session_user_id, profile_updates); add_emotion_record(session_user_id, emotion)
initial_input = f"Hi Aishura! I'm {name} from {location}. Focusing on '{cleaned_goal}' in {industry} ({exp_level}, {work_style}). Feeling {emotion}. Help me start?"
# Get the first response (streamed) and accumulate it
ai_response_full = "".join(chunk for chunk in get_ai_response_stream(session_user_id, initial_input))
initial_chat_display = [[initial_input, ai_response_full]]
e_fig, p_fig, r_fig, s_fig = create_emotion_chart(session_user_id), create_progress_chart(session_user_id), create_routine_completion_gauge(session_user_id), create_skill_radar_chart(session_user_id)
gen_recommendations_simple(session_user_id); recs_md = display_recommendations(session_user_id)
return (gr.update(value=initial_chat_display), gr.update(visible=False), gr.update(visible=True), gr.update(value=e_fig), gr.update(value=p_fig), gr.update(value=r_fig), gr.update(value=s_fig), gr.update(value=recs_md))
def chat_submit_stream(message_text, history_list_list):
"""Handles chatbot submission, yields streamed AI response chunks."""
logger.info(f"Chat submit stream v5 for {session_user_id}: '{message_text[:50]}...'")
if not message_text:
yield history_list_list, gr.update() # No change if empty message
return
# Append user message and placeholder for assistant response
history_list_list.append([message_text, ""])
yield history_list_list, gr.update() # Update UI immediately
# Stream AI response and update the placeholder chunk by chunk
full_response = ""
try:
for chunk in get_ai_response_stream(session_user_id, message_text):
full_response += chunk
history_list_list[-1][1] = full_response # Update the last message in history
yield history_list_list, gr.update() # Yield updated history to Gradio
except Exception as e:
logger.error(f"Error during AI response streaming: {e}")
history_list_list[-1][1] = f"Sorry, an error occurred while generating the response: {e}"
yield history_list_list, gr.update() # Show error in chat
# After streaming finishes (or errors out), generate recommendations
try:
gen_recommendations_simple(session_user_id)
recs_md = display_recommendations(session_user_id)
except Exception as e:
logger.error(f"Error generating recommendations: {e}")
recs_md = "Error loading recommendations."
# Yield final state with recommendations updated
yield history_list_list, gr.update(value=recs_md)
# --- Tool Interface Handlers (Identical to v4) ---
def generate_template_interface_handler(doc_type, career_field, experience):
logger.info(f"Manual Template UI v5: type='{doc_type}'")
json_str = generate_document_template(doc_type, career_field, experience)
try: return json.loads(json_str).get('template_markdown', "Error.")
except: return "Error displaying template."
def create_routine_interface_handler(emotion, goal, time_available, days):
logger.info(f"Manual Routine UI v5: emo='{emotion}', goal='{goal}'")
cleaned_emotion = emotion.split(" ")[0] if " " in emotion else emotion
json_str = create_personalized_routine(cleaned_emotion, goal, int(time_available), int(days))
try:
data = json.loads(json_str)
if "error" in data: return f"Error: {data['error']}", gr.update()
add_routine_to_user(session_user_id, data)
md = f"# {data.get('name', 'Your Routine')}\n\n_{data.get('support_message', data.get('description', ''))}_\n\n---\n\n"
for day in data.get('daily_tasks', []):
md += f"## Day {day.get('day', '?')}\n"; tasks = day.get('tasks', [])
if not tasks: md += "- Rest day or catch-up.\n"
else:
for task in tasks: md += f"- **{task.get('name', 'Task')}** ({task.get('duration', '?')} min)\n - _{task.get('description', '...')}_\n"
md += "\n"
gauge = create_routine_completion_gauge(session_user_id)
return md, gr.update(value=gauge)
except Exception as e: logger.exception("Error displaying routine"); return f"Error displaying routine: {e}", gr.update()
def analyze_resume_interface_handler(resume_file):
logger.info(f"Manual Resume Analysis UI v5: file={resume_file}")
if resume_file is None: return "Please upload resume.", gr.update(value=None), gr.update(value=None)
try:
# Gradio File object has .name attribute for the temp path
with open(resume_file.name, 'r', encoding='utf-8') as f: resume_text = f.read()
except Exception as e: logger.error(f"Error reading file: {e}"); return f"Error reading file: {e}", gr.update(value=None), gr.update(value=None)
if not resume_text: return "Resume empty.", gr.update(value=None), gr.update(value=None)
profile = get_user_profile(session_user_id); goal = profile.get('career_goal', 'Not specified')
resume_path = save_user_resume(session_user_id, resume_text)
if not resume_path: return "Could not save resume.", gr.update(value=None), gr.update(value=None)
analysis_json_str = analyze_resume(resume_text, goal)
try:
analysis_result = json.loads(analysis_json_str); analysis = analysis_result.get('analysis', {})
md = f"## Resume Analysis (Simulated)\n\n**Goal:** '{goal}'\n\n**Strengths:**\n" + "\n".join([f"* {s}" for s in analysis.get('strengths', ["N/A"])]) + "\n\n**Improvements:**\n" + "\n".join([f"* {s}" for s in analysis.get('areas_for_improvement', ["N/A"])]) + f"\n\n**Format:** {analysis.get('format_feedback', 'N/A')}\n**Content:** {analysis.get('content_feedback', 'N/A')}\n**Keywords:** {', '.join(analysis.get('keyword_suggestions', []))}\n\n**Next Steps:**\n" + "\n".join([f"* {s}" for s in analysis.get('next_steps', [])])
skill_fig = create_skill_radar_chart(session_user_id)
return md, gr.update(value=skill_fig), gr.update(value=resume_path)
except Exception as e: logger.exception("Error formatting analysis."); return "Error displaying analysis.", gr.update(value=None), gr.update(value=None)
def analyze_portfolio_interface_handler(portfolio_url, portfolio_description):
logger.info(f"Manual Portfolio Analysis UI v5: url='{portfolio_url}'")
if not portfolio_description: return "Provide description."
profile = get_user_profile(session_user_id); goal = profile.get('career_goal', 'Not specified')
portfolio_path = save_user_portfolio(session_user_id, portfolio_url, portfolio_description)
if not portfolio_path: return "Could not save details."
analysis_json_str = analyze_portfolio(portfolio_description, goal, portfolio_url)
try:
analysis_result = json.loads(analysis_json_str); analysis = analysis_result.get('analysis', {})
md = f"## Portfolio Analysis (Simulated)\n\n**Goal:** '{goal}'\n"; md += f"**URL:** {portfolio_url}\n\n" if portfolio_url else "\n"; md += f"**Alignment:** {analysis.get('alignment_with_goal', 'N/A')}\n\n**Strengths:**\n" + "\n".join([f"* {s}" for s in analysis.get('strengths', [])]) + "\n\n**Improvements:**\n" + "\n".join([f"* {s}" for s in analysis.get('areas_for_improvement', [])]) + f"\n\n**Presentation:** {analysis.get('presentation_feedback', 'N/A')}\n\n**Next Steps:**\n" + "\n".join([f"* {s}" for s in analysis.get('next_steps', [])])
return md
except Exception as e: logger.exception("Error formatting analysis."); return "Error displaying analysis."
# --- Progress Tracking Handlers (Identical to v4) ---
def complete_task_handler(task_name):
logger.info(f"Complete Task UI v5: task='{task_name}'")
if not task_name: return ("Enter task name.", "", gr.update(), gr.update(), gr.update())
updated_profile = add_task_to_user(session_user_id, task_name)
if updated_profile and updated_profile.get('routine_history'):
db = load_user_database(); profile = db.get('users', {}).get(session_user_id)
if profile and profile.get('routine_history'): latest_routine = profile['routine_history'][0]; increment = random.randint(5, 15); latest_routine['completion'] = min(100, latest_routine.get('completion', 0) + increment); save_user_database(db)
e_fig, p_fig, g_fig = create_emotion_chart(session_user_id), create_progress_chart(session_user_id), create_routine_completion_gauge(session_user_id)
return (f"Great job on '{task_name}'!", "", gr.update(value=e_fig), gr.update(value=p_fig), gr.update(value=g_fig))
def update_emotion_handler(emotion):
logger.info(f"Update Emotion UI v5: emotion='{emotion}'")
if not emotion: return "Select emotion.", gr.update()
add_emotion_record(session_user_id, emotion); e_fig = create_emotion_chart(session_user_id)
cleaned_display = emotion.split(" ")[0] if " " in emotion else emotion
return f"Got it. Feeling ({cleaned_display}) acknowledged.", gr.update(value=e_fig)
def display_recommendations(current_user_id):
# (Identical to v4)
logger.info(f"Displaying recommendations v5 for {current_user_id}")
profile = get_user_profile(current_user_id); recs = profile.get('recommendations', [])
if not recs: return "Chat with me for next steps! 😊"
pending_recs = [r for r in recs if r.get('status') == 'pending'][:5]
if not pending_recs: return "No pending recommendations. Nice!"
md = "### ✨ Focus Areas:\n\n"
for i, entry in enumerate(pending_recs, 1): rec = entry.get('recommendation', {}); md += f"**{i}. {rec.get('title', 'Rec')}**\n - {rec.get('description', '')}\n - *Pri: {rec.get('priority', 'Med')} | Type: {rec.get('action_type', 'Gen')}*\n---\n"
return md
# --- Build Gradio Interface (Structure identical to v4) ---
with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky", secondary_hue="blue", font=[gr.themes.GoogleFont("Poppins"), "Arial", "sans-serif"]), title="Aishura v5 (Groq)") as app:
gr.Markdown("# Aishura - Your Empathetic AI Career Copilot πŸš€")
# ** Updated Subtitle **
gr.Markdown("_Powered by Groq Llama3 70B & Real-Time Data_")
# Welcome Screen
with gr.Group(visible=True) as welcome_group:
gr.Markdown("## Welcome! Let's personalize your journey."); gr.Markdown("Tell me about yourself.")
with gr.Row():
with gr.Column(): name_input = gr.Textbox(label="First name?"); location_input = gr.Textbox(label="Location (City, Country)?", placeholder="e.g., Jeddah, SA"); industry_input = gr.Textbox(label="Primary industry?", placeholder="e.g., Tech, Healthcare")
with gr.Column(): emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling?"); goal_dropdown = gr.Dropdown(choices=GOAL_TYPES, label="Main career goal?"); exp_level_dropdown = gr.Dropdown(choices=["Student", "Entry-Level (0-2 yrs)", "Mid-Level (3-7 yrs)", "Senior-Level (8+ yrs)", "Executive"], label="Experience level?"); work_style_dropdown = gr.Dropdown(choices=["On-site", "Hybrid", "Remote", "Any"], label="Preferred work style?", value="Any")
welcome_button = gr.Button("✨ Start My Journey ✨", variant="primary"); welcome_output = gr.Markdown()
# Main Interface
with gr.Group(visible=False) as main_interface:
with gr.Tabs():
# Chat Tab
with gr.TabItem("πŸ’¬ Chat with Aishura"):
with gr.Row():
with gr.Column(scale=3):
chatbot_display = gr.Chatbot(label="Aishura", height=600, show_copy_button=True, bubble_full_width=False, avatar_images=(None, "https://img.icons8.com/external-those-icons-lineal-color-those-icons/96/external-AI-artificial-intelligence-those-icons-lineal-color-those-icons-9.png"))
msg_textbox = gr.Textbox(show_label=False, placeholder="Type your message here...", container=False, scale=1)
with gr.Column(scale=1):
gr.Markdown("### Recommendations"); recommendation_output = gr.Markdown("Loading...")
refresh_recs_button = gr.Button("πŸ”„ Refresh Recs"); gr.Markdown("---"); gr.Markdown("### Quick Actions")
# Analysis & Tools Tab
with gr.TabItem("πŸ› οΈ Analyze & Tools"):
with gr.Tabs():
with gr.TabItem("πŸ“„ Resume Hub"):
gr.Markdown("### Analyze Resume"); gr.Markdown("Upload resume (TXT/PDF) for analysis.")
resume_file_input = gr.File(label="Upload Resume (.txt, .pdf)", file_types=['.txt', '.pdf']); resume_path_display = gr.Textbox(label="Current Resume File", interactive=False)
analyze_resume_button = gr.Button("Analyze Uploaded Resume", variant="primary"); resume_analysis_output = gr.Markdown("Analysis...")
gr.Markdown("---"); gr.Markdown("### Generate Templates")
doc_type_dropdown = gr.Dropdown(choices=["Resume", "Cover Letter", "LinkedIn Summary", "Networking Email"], label="Doc Type"); doc_field_input = gr.Textbox(label="Field?", placeholder="e.g., SWE"); doc_exp_dropdown = gr.Dropdown(choices=["Student", "Entry-Level", "Mid-Level", "Senior-Level"], label="Level?")
generate_template_button = gr.Button("Generate Template"); template_output_md = gr.Markdown("Template...")
with gr.TabItem("🎨 Portfolio Hub"):
gr.Markdown("### Analyze Portfolio")
portfolio_url_input = gr.Textbox(label="URL?", placeholder="https://yourportfolio.com"); portfolio_desc_input = gr.Textbox(label="Description?", lines=5, placeholder="e.g., Web dev projects...")
analyze_portfolio_button = gr.Button("Analyze Portfolio Info", variant="primary"); portfolio_analysis_output = gr.Markdown("Analysis...")
with gr.TabItem("πŸ“… Routine Builder"):
gr.Markdown("### Create Routine"); gr.Markdown("Build a manageable routine.")
routine_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="Feeling?"); profile = get_user_profile(session_user_id); routine_goal_input = gr.Textbox(label="Goal?", value=profile.get('career_goal', ''))
routine_time_slider = gr.Slider(15, 120, 45, step=15, label="Mins/day?"); routine_days_slider = gr.Slider(3, 21, 7, step=1, label="Days?")
create_routine_button = gr.Button("Create Routine", variant="primary"); routine_output_md = gr.Markdown("Routine...")
# Progress Tab
with gr.TabItem("πŸ“ˆ Track Your Journey"):
gr.Markdown("## Progress Dashboard")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### βœ… Log Task"); task_input = gr.Textbox(label="Accomplishment?", placeholder="e.g., Updated resume")
complete_button = gr.Button("Log Task", variant="primary"); task_output = gr.Markdown()
gr.Markdown("---"); gr.Markdown("### 😊 Feeling now?")
new_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="Select emotion"); emotion_button = gr.Button("Update Emotion"); emotion_output = gr.Markdown()
with gr.Column(scale=2):
gr.Markdown("### Emotional Journey"); emotion_chart_output = gr.Plot(label="Emotion Trend")
gr.Markdown("### Routine Progress"); routine_gauge_output = gr.Plot(label="Routine Completion")
with gr.Row():
with gr.Column(scale=1): gr.Markdown("### Progress Points"); progress_chart_output = gr.Plot(label="Points Over Time")
with gr.Column(scale=1): gr.Markdown("### Skills (from Resume)"); skill_radar_chart_output = gr.Plot(label="Skills Radar")
# --- Event Wiring (Using streaming chat submit) ---
welcome_button.click(fn=welcome, inputs=[name_input, location_input, emotion_dropdown, goal_dropdown, industry_input, exp_level_dropdown, work_style_dropdown], outputs=[chatbot_display, welcome_group, main_interface, emotion_chart_output, progress_chart_output, routine_gauge_output, skill_radar_chart_output, recommendation_output])
# Use the streaming chat submit function
msg_textbox.submit(
fn=chat_submit_stream, # Use the streaming version
inputs=[msg_textbox, chatbot_display],
outputs=[chatbot_display, recommendation_output] # chatbot updates progressively, recs at end
).then(lambda: gr.update(value=""), outputs=[msg_textbox]) # Clear textbox after submit
refresh_recs_button.click(fn=lambda: display_recommendations(session_user_id), outputs=[recommendation_output])
analyze_resume_button.click(fn=analyze_resume_interface_handler, inputs=[resume_file_input], outputs=[resume_analysis_output, skill_radar_chart_output, resume_path_display])
analyze_portfolio_button.click(fn=analyze_portfolio_interface_handler, inputs=[portfolio_url_input, portfolio_desc_input], outputs=[portfolio_analysis_output])
generate_template_button.click(fn=generate_template_interface_handler, inputs=[doc_type_dropdown, doc_field_input, doc_exp_dropdown], outputs=[template_output_md])
create_routine_button.click(fn=create_routine_interface_handler, inputs=[routine_emotion_dropdown, routine_goal_input, routine_time_slider, routine_days_slider], outputs=[routine_output_md, routine_gauge_output])
complete_button.click(fn=complete_task_handler, inputs=[task_input], outputs=[task_output, task_input, emotion_chart_output, progress_chart_output, routine_gauge_output])
emotion_button.click(fn=update_emotion_handler, inputs=[new_emotion_dropdown], outputs=[emotion_output, emotion_chart_output])
return app
# --- Main Execution ---
if __name__ == "__main__":
print("\n--- Aishura v5 (Groq Streaming) Configuration Check ---")
if not GROQ_API_KEY: print("⚠️ WARNING: GROQ_API_KEY not found. AI features DISABLED.")
else: print("βœ… GROQ_API_KEY found.")
if not SERPER_API_KEY: print("⚠️ WARNING: SERPER_API_KEY not found. Live web search DISABLED.")
else: print("βœ… SERPER_API_KEY found.")
if not client: print("❌ ERROR: Groq client failed to initialize. AI features DISABLED.")
# ** Updated Model Name in Check **
else: print(f"βœ… Groq client initialized for model '{MODEL_ID}'.")
print("---------------------------------------------------\n")
logger.info("Starting Aishura v5 (Groq Streaming) Gradio application...")
aishura_app = create_interface()
# Consider adding server_name="0.0.0.0" to allow access from local network if needed
aishura_app.launch(share=False, debug=False)
logger.info("Aishura Gradio application stopped.")