AIShurA / app.py
ans123's picture
Update app.py
b0a1bba verified
raw
history blame
55.5 kB
# filename: app_openai_corrected_v2.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 # Keep for potential future internal API calls
from typing import List, Dict, Any, Optional
import logging
from dotenv import load_dotenv
import uuid
import re
import openai
# --- 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 ---
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
logger.warning("OPENAI_API_KEY not found. AI features will not work.")
# --- Initialize the OpenAI client ---
try:
client = openai.OpenAI(api_key=OPENAI_API_KEY)
logger.info("OpenAI client initialized successfully.")
except Exception as e:
logger.error(f"Failed to initialize OpenAI client: {e}")
client = None
# --- Model configuration ---
MODEL_ID = "gpt-4o"
# --- Constants ---
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"
os.makedirs(RESUME_FOLDER, exist_ok=True)
os.makedirs(PORTFOLIO_FOLDER, exist_ok=True)
# --- Tool Definitions for OpenAI ---
tools_list = [
{
"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"}, "career_field": {"type": "string"}, "experience_level": {"type": "string"} }, "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"}, "goal": {"type": "string"}, "available_time_minutes": {"type": "integer"}, "routine_length_days": {"type": "integer"} }, "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.",
"parameters": { "type": "object", "properties": { "resume_text": {"type": "string"}, "career_goal": {"type": "string"} }, "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"}, "portfolio_description": {"type": "string"}, "career_goal": {"type": "string"} }, "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.",
"parameters": { "type": "object", "properties": { "resume_text": {"type": "string"}, "max_skills": {"type": "integer"} }, "required": ["resume_text"] },
}
}
]
# --- User Database Functions ---
def load_user_database():
try:
with open(USER_DB_PATH, 'r', encoding='utf-8') as file: db = json.load(file)
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']:
if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
if msg['role'] in ['user', 'assistant'] and msg['content'] is not None and not isinstance(msg['content'], str): msg['content'] = str(msg['content'])
fixed_history.append(msg)
elif isinstance(msg, dict) and msg.get('role') == 'tool' and all(k in msg for k in ['tool_call_id', 'name', 'content']):
if not isinstance(msg['content'], str): msg['content'] = json.dumps(msg['content']) if msg['content'] is not None else ""
fixed_history.append(msg)
else: logger.warning(f"Skipping invalid chat message structure for user {user_id}: {msg}")
profile['chat_history'] = fixed_history
if 'recommendations' not in profile or not isinstance(profile['recommendations'], list): profile['recommendations'] = []
return db
except (FileNotFoundError, json.JSONDecodeError): logger.info(f"DB file '{USER_DB_PATH}' not found/invalid. Creating new."); db = {'users': {}}; save_user_database(db); return db
except Exception as e: logger.error(f"Error loading DB from {USER_DB_PATH}: {e}"); return {'users': {}}
def save_user_database(db):
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):
db = load_user_database()
if user_id not in db.get('users', {}):
db['users'] = db.get('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().isoformat() }
save_user_database(db)
profile = db.get('users', {}).get(user_id, {})
if 'chat_history' not in profile or not isinstance(profile.get('chat_history'), list): profile['chat_history'] = []
if 'recommendations' not in profile or not isinstance(profile.get('recommendations'), list): profile['recommendations'] = []
if 'daily_emotions' not in profile or not isinstance(profile.get('daily_emotions'), list): profile['daily_emotions'] = []
if 'completed_tasks' not in profile or not isinstance(profile.get('completed_tasks'), list): profile['completed_tasks'] = []
if 'routine_history' not in profile or not isinstance(profile.get('routine_history'), list): profile['routine_history'] = []
return profile
def update_user_profile(user_id, updates):
db = load_user_database()
if user_id in db.get('users', {}):
profile = db['users'][user_id]
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() }
profile['completed_tasks'].append(task_with_date)
profile['progress_points'] = profile.get('progress_points', 0) + random.randint(10, 25)
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: days_delta = 7
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, content_or_struct):
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
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}'"); return profile
# Prepare content based on role
content = content_or_struct
if role == 'assistant':
# Handle the structure passed for assistant (potentially including tool calls)
content = content_or_struct.get('content', '') if isinstance(content_or_struct, dict) else str(content_or_struct)
if isinstance(content_or_struct, dict) and content_or_struct.get('tool_calls'):
# Store the structure if there are tool calls
content = content_or_struct # Keep the dict
elif content is None: content = "" # Store empty string if no text and no tool calls
elif role == 'tool':
# Content should be the string result from the tool
if not isinstance(content_or_struct.get('content'), str):
content_or_struct['content'] = json.dumps(content_or_struct.get('content')) if content_or_struct.get('content') is not None else ""
content = content_or_struct # Store the dict for tool message
elif not content_or_struct and role == 'user': logger.warning("Empty user message."); return profile # Skip empty user messages
chat_message = {"role": role, "content": content, "timestamp": datetime.now().isoformat()}
profile['chat_history'].append(chat_message)
# Limit history
max_history = 50
if len(profile['chat_history']) > max_history:
system_msgs = [m for m in profile['chat_history'] if m['role'] == 'system']
other_msgs = [m for m in profile['chat_history'] if m['role'] != 'system']
profile['chat_history'] = system_msgs + other_msgs[-max_history:]
save_user_database(db); return profile
return None
# --- Basic Routine Fallback Function ---
def generate_basic_routine(emotion, goal, available_time=60, days=7):
"""Generate a basic routine as fallback."""
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"]
if "job" in goal.lower() or "internship" in goal.lower() or "company" in goal.lower(): base_type = "job_search"
elif "skill" in goal.lower() or "learn" in goal.lower(): base_type = "skill_building"
elif "network" in goal.lower(): base_type = "job_search"
else: base_type = "skill_building"
include_wellbeing = cleaned_emotion in negative_emotions
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["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 basic {days}-day plan focusing on '{goal}' while acknowledging feeling {cleaned_emotion}.", "days": days, "daily_tasks": daily_tasks_list}
return routine
# --- Tool Implementation Functions ---
def generate_document_template(document_type: str, career_field: str = "", experience_level: str = "") -> str:
"""Generates a basic markdown template for the specified document type."""
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"
template += f"**Target Field:** {career_field or 'Not specified'}\n"
template += f"**Experience Level:** {experience_level or 'Not specified'}\n\n---\n\n"
# Use triple quotes for multi-line strings to fix syntax errors
if "resume" in document_type.lower():
template += """
### Contact Information
- Name:
- Phone:
- Email:
- LinkedIn URL:
- Portfolio URL (Optional):
### Summary/Objective
_[ 2-3 sentences summarizing your key skills, experience, and career goals, tailored to the job/field. ]_
### Experience
**Company Name** | Location | Job Title | _Start Date – End Date_
- Accomplishment 1 (Use action verbs and quantify results, e.g., 'Increased sales by 15%...')
- Accomplishment 2
_[ Repeat for other relevant positions ]_
### Education
**University/Institution Name** | Degree | _Graduation Date (or Expected)_
- Relevant coursework, honors, activities (Optional)
### Skills
- **Technical Skills:** [ e.g., Python, Java, SQL, MS Excel, Google Analytics ]
- **Languages:** [ e.g., English (Native), Spanish (Fluent) ]
- **Other:** [ Certifications, relevant tools ]
"""
elif "cover letter" in document_type.lower():
# Corrected syntax using triple quotes
template += """
[Your Name]
[Your Address]
[Your Phone]
[Your Email]
[Date]
[Hiring Manager Name (if known), or 'Hiring Team']
[Hiring Manager Title (if known)]
[Company Name]
[Company Address]
**Subject: Application for [Job Title] Position - [Your Name]**
Dear [Mr./Ms./Mx. Last Name or Hiring Team],
**Introduction:** State the position you are applying for and where you saw the advertisement. Briefly express your enthusiasm for the role and the company. Mention 1-2 key qualifications that make you a strong fit.
_[ 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], I am confident I possess the skills and experience necessary to excel in this role and contribute significantly to [Company Name]. ]_
**Body Paragraph(s):** Elaborate on your qualifications and experiences, directly addressing the requirements listed in the job description. Provide specific examples (using the STAR method implicitly can be effective). Explain why you are interested in *this specific* company and role. Show you've done your research.
_[ Example: In my previous role at [Previous Company], I was responsible for [Responsibility relevant to new job]. I successfully [Quantifiable achievement relevant to new job], demonstrating my ability to [Skill required by new job]. I am particularly drawn to [Company Name]'s work in [Specific area company works in], as described in [Source, e.g., recent news, company website], and I believe my [Relevant skill/experience] would be a valuable asset to your team. ]_
**Conclusion:** Reiterate your strong interest and suitability for the role. Briefly summarize your key strengths. State your call to action (e.g., "I am eager to discuss my qualifications further..."). Thank the reader for their time and consideration.
_[ Example: Thank you for considering my application. My resume provides further detail on my qualifications. I am excited about the opportunity to contribute to [Company Name] and look forward to hearing from you soon. ]_
Sincerely,
[Your Typed Name]
"""
elif "linkedin summary" in document_type.lower():
template += """
### LinkedIn Summary/About Section Template
**Headline:** [ A concise, keyword-rich description of your professional identity, e.g., 'Software Engineer specializing in AI | Python | Cloud Computing | Seeking Innovative Opportunities' ]
**About Section:**
_[ Paragraph 1: Hook & Overview. Start with a compelling statement about your passion, expertise, or career mission. Briefly introduce who you are professionally and your main areas of focus. Use keywords relevant to your field and desired roles. ]_
_[ Paragraph 2: Key Skills & Experience Highlights. Detail your core competencies and technical/soft skills. Mention key experiences or types of projects you've worked on. Quantify achievements where possible. Tailor this to the audience you want to attract (recruiters, clients, peers). ]_
_[ Paragraph 3: Career Goals & What You're Seeking (Optional but recommended). Briefly state your career aspirations or the types of opportunities, connections, or collaborations you are looking for. ]_
_[ Paragraph 4: Call to Action / Personality (Optional). You might end with an invitation to connect, mention personal interests related to your field, or add a touch of personality. ]_
**Specialties/Keywords:** [ List 5-10 key terms related to your skills and industry, e.g., Project Management, Data Analysis, Agile Methodologies, Content Strategy, Java, Cloud Security ]
"""
else:
template += "_[ Basic structure for this document type will be provided here. ]_"
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:
"""Creates a personalized routine, falling back to basic generation if needed."""
logger.info(f"Tool: create_personalized_routine(emo='{emotion}', goal='{goal}', time={available_time_minutes}, days={routine_length_days})")
try:
logger.warning("Using basic fallback for create_personalized_routine.")
routine = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days)
if not routine: raise ValueError("Basic routine generation failed.")
return json.dumps(routine)
except Exception as e:
logger.error(f"Error in create_personalized_routine: {e}")
try: routine = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days); return json.dumps(routine) if routine else json.dumps({"error": "Failed."})
except Exception as fallback_e: logger.error(f"Fallback failed: {fallback_e}"); return json.dumps({"error": f"Failed: {e}"})
def analyze_resume(resume_text: str, career_goal: str) -> str:
"""Provides analysis of the resume using AI (Simulated)."""
logger.info(f"Tool: analyze_resume(goal='{career_goal}', len={len(resume_text)})")
logger.warning("Using placeholder for analyze_resume.")
analysis = { "analysis": { "strengths": ["Placeholder: Clear summary.", "Placeholder: Action verbs used."], "areas_for_improvement": ["Placeholder: Quantify results more.", f"Placeholder: Tailor skills for '{career_goal}'."], "format_feedback": "Placeholder: Clean format.", "content_feedback": f"Placeholder: Content partially relevant to '{career_goal}'.", "keyword_suggestions": ["Placeholder: Add 'Keyword1', 'Keyword2'."], "next_steps": ["Placeholder: Refine role descriptions.", "Placeholder: Add project section?"] } }
return json.dumps(analysis)
def analyze_portfolio(portfolio_description: str, career_goal: str, portfolio_url: str = "") -> str:
"""Provides analysis of the portfolio using AI (Simulated)."""
logger.info(f"Tool: analyze_portfolio(goal='{career_goal}', url='{portfolio_url}', desc_len={len(portfolio_description)})")
logger.warning("Using placeholder for analyze_portfolio.")
analysis = { "analysis": { "alignment_with_goal": f"Placeholder: Moderate alignment with '{career_goal}'.", "strengths": ["Placeholder: Project variety.", "Placeholder: Clear description."], "areas_for_improvement": ["Placeholder: Link projects to goal skills.", "Placeholder: Add case study depth?"], "presentation_feedback": f"Placeholder: Check URL ({portfolio_url}) if provided.", "next_steps": ["Placeholder: Feature 2-3 best projects.", "Placeholder: Get peer feedback."] } }
return json.dumps(analysis)
def extract_and_rate_skills_from_resume(resume_text: str, max_skills: int = 8) -> str:
"""Extracts and rates skills from resume text (Simulated)."""
logger.info(f"Tool: extract_skills(len={len(resume_text)}, max={max_skills})")
logger.warning("Using placeholder for extract_skills.")
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"]
found = []
resume_lower = resume_text.lower()
for skill in possible:
if re.search(r'\b' + re.escape(skill.lower()) + r'\b', resume_lower): found.append({"name": skill, "score": random.randint(4, 9)})
if len(found) >= max_skills: break
if not found and len(resume_text) > 50: 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]})
# --- AI Interaction Logic (Using OpenAI) ---
def get_ai_response(user_id: str, user_input: str, generate_recommendations: bool = True) -> str:
"""Gets response from OpenAI, handling context, system prompt, and tool calls."""
logger.info(f"Getting AI response for user {user_id}. Input: '{user_input[:100]}...'")
if not client: return "AI service unavailable. Check configuration."
try:
user_profile = get_user_profile(user_id)
if not user_profile: logger.error(f"Failed profile retrieval for {user_id}."); return "Cannot access profile."
current_emotion_display = user_profile.get('current_emotion', 'Not specified')
system_prompt = f"""
You are Aishura, an emotionally intelligent AI career assistant. Goal: provide empathetic, realistic, actionable guidance. Steps:
1. Acknowledge message & emotion ("I understand you're feeling {current_emotion_display}..."). Be empathetic.
2. Address query directly.
3. Proactively offer support via tools: generate templates (`generate_document_template`), create routines (`create_personalized_routine`), analyze resume/portfolio (`analyze_resume`, `analyze_portfolio`) if relevant.
4. **Job Suggestions:** If asked for jobs, **DO NOT use a tool**. Generate 2-3 plausible job titles/roles based on goal ('{user_profile.get('career_goal', 'Not specified')}') and location ('{user_profile.get('location', 'Not specified')}'). Mention resume skill alignment (resume path: '{user_profile.get('resume_path', '')}'). State they are examples, not live listings.
5. Tailor to profile: Name: {user_profile.get('name', 'User')}, Location: {user_profile.get('location', 'N/A')}, Goal: {user_profile.get('career_goal', 'N/A')}.
6. If resume/portfolio uploaded, mention analysis possibility. User must ask or provide content.
7. Be concise, friendly, focus on next steps. Use markdown.
8. If a tool fails, inform user gracefully ("I couldn't generate the template...") & suggest alternatives. No raw errors.
"""
# Build Message History
messages = [{"role": "system", "content": system_prompt}]
chat_history = user_profile.get('chat_history', [])
for msg in chat_history:
# Ensure message structure is valid before appending
if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
# Handle tool calls stored in content for assistant role
content = msg['content']
role = msg['role']
tool_calls_in_msg = None
if role == 'assistant' and isinstance(content, dict) and 'tool_calls' in content:
tool_calls_in_msg = content['tool_calls']
content = content.get('content', '') # Get text content part
# Append message, reconstructing tool calls if needed
msg_to_append = {"role": role, "content": content if content is not None else ""}
if tool_calls_in_msg:
msg_to_append['tool_calls'] = tool_calls_in_msg
messages.append(msg_to_append)
elif isinstance(msg, dict) and msg.get('role') == 'tool' and all(k in msg for k in ['tool_call_id', 'name', 'content']):
tool_content = msg['content'] if isinstance(msg['content'], str) else json.dumps(msg['content'])
messages.append({ "role": "tool", "tool_call_id": msg['tool_call_id'], "name": msg['name'], "content": tool_content })
messages.append({"role": "user", "content": user_input})
# Initial API Call
logger.info(f"Sending {len(messages)} messages to OpenAI model {MODEL_ID}.")
response = client.chat.completions.create( model=MODEL_ID, messages=messages, tools=tools_list, tool_choice="auto", temperature=0.7, max_tokens=1500 )
response_message = response.choices[0].message
# Prepare assistant's response for DB (might include tool calls)
assistant_response_for_db = { "role": "assistant", "content": response_message.content }
if response_message.tool_calls:
assistant_response_for_db['tool_calls'] = [tc.model_dump() for tc in response_message.tool_calls]
final_response_content = response_message.content
tool_calls = response_message.tool_calls
# Tool Call Handling
if tool_calls:
logger.info(f"AI requested tool call(s): {[tc.function.name for tc in tool_calls]}")
messages.append(response_message) # Add assistant's msg with tool_calls to local list
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, }
tool_results_for_api = []
tool_results_for_db = [] # To store separately for DB
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions.get(function_name)
try:
function_args = json.loads(tool_call.function.arguments)
if function_to_call:
if function_name == "analyze_resume":
if 'career_goal' not in function_args: function_args['career_goal'] = user_profile.get('career_goal', 'N/A')
save_user_resume(user_id, function_args.get('resume_text', ''))
if function_name == "analyze_portfolio":
if 'career_goal' not in function_args: function_args['career_goal'] = user_profile.get('career_goal', 'N/A')
save_user_portfolio(user_id, function_args.get('portfolio_url', ''), function_args.get('portfolio_description', ''))
logger.info(f"Calling function '{function_name}' with args: {function_args}")
function_response = function_to_call(**function_args)
logger.info(f"Function '{function_name}' returned: {function_response[:200]}...")
tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": function_response }
else:
logger.warning(f"Function {function_name} not implemented.")
tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "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}")
tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": json.dumps({"error": f"Invalid tool arguments."}) }
except Exception as e:
logger.exception(f"Error executing {function_name}: {e}")
tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": json.dumps({"error": f"Failed tool {function_name}."}) }
messages.append(tool_result) # Append full dict to local messages
tool_results_for_db.append(tool_result) # Store for DB
# Second API Call
logger.info(f"Sending {len(messages)} messages to OpenAI (incl. tool results).")
second_response = client.chat.completions.create( model=MODEL_ID, messages=messages, temperature=0.7, max_tokens=1500 )
final_response_content = second_response.choices[0].message.content
logger.info("Received final response after tool calls.")
# Store Interaction Sequence in DB
add_chat_message(user_id, "user", user_input)
add_chat_message(user_id, "assistant", assistant_response_for_db) # Store first assistant msg (with tool calls)
for res in tool_results_for_db: add_chat_message(user_id, "tool", res) # Store tool results
add_chat_message(user_id, "assistant", {"role": "assistant", "content": final_response_content}) # Store final text response
else: # No Tool Calls
logger.info("No tool calls requested.")
add_chat_message(user_id, "user", user_input)
add_chat_message(user_id, "assistant", assistant_response_for_db) # Store the only assistant response
# Post-processing
if not final_response_content: final_response_content = "Action complete. How else can I help?"
# Skipping inline recommendation generation
# if generate_recommendations: try: pass except Exception: pass
return final_response_content
except openai.APIError as e: logger.error(f"OpenAI API Error: {e.status_code} - {e.response}"); return f"AI service error (Code: {e.status_code}). Try again."
except openai.APITimeoutError: logger.error("OpenAI timed out."); return "AI service request timed out. Try again."
except openai.APIConnectionError as e: logger.error(f"OpenAI Connection Error: {e}"); return "Cannot connect to AI service."
except openai.RateLimitError: logger.error("OpenAI Rate Limit Exceeded."); return "AI service busy. Try again shortly."
except Exception as e: logger.exception(f"Unexpected error in get_ai_response: {e}"); return "Unexpected error occurred."
# --- Recommendation Generation (Placeholder) ---
def gen_recommendations_openai(user_id, user_input, ai_response):
"""Generate recommendations using OpenAI."""
logger.info(f"Generating recommendations for user {user_id}")
if not client: return []
# (Keep implementation from previous version) ...
return [] # Keep disabled for now
# --- Chart and Visualization Functions ---
# (Keep create_emotion_chart, create_progress_chart, create_routine_completion_gauge, create_skill_radar_chart - unchanged from previous corrected version)
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.", showarrow=False); fig.update_layout(title="Emotion Tracking"); return fig
vals = {"Unmotivated": 1, "Anxious": 2, "Confused": 3, "Discouraged": 4, "Overwhelmed": 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="Emotional Journey")
fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}<br>Feeling: %{text}', 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.", showarrow=False); fig.update_layout(title="Progress"); return fig
tasks.sort(key=lambda x: datetime.fromisoformat(x['date']))
dates, points, labels, cum_pts = [], [], [], 0; pts_task = 20
for task in tasks: dates.append(datetime.fromisoformat(task['date'])); cum_pts += task.get('points', pts_task); points.append(cum_pts); labels.append(task['task'])
df = pd.DataFrame({'Date': dates, 'Points': points, 'Task': labels})
fig = px.line(df, x='Date', y='Points', markers=True, title="Progress Journey"); fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}<br>Points: %{y}<br>Task: %{text}', text=df['Task']); 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': "Routine"})); fig.add_annotation(text="No routine.", 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 for skill chart."); fig = go.Figure(); fig.add_annotation(text="Analyze Resume for Skill Chart", showarrow=False); fig.update_layout(title="Skills"); return fig
try:
with open(path, 'r', encoding='utf-8') as f: text = f.read()
skills_json = extract_and_rate_skills_from_resume(resume_text=text); data = json.loads(skills_json)
if 'skills' in data and data['skills']:
skills = data['skills'][:8]; cats = [s['name'] for s in skills]; vals = [s['score'] for s in skills]
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'))
fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 10])), showlegend=False, title="Skill Assessment (Simulated)")
logger.info(f"Created radar chart with {len(skills)} skills."); return fig
else: logger.warning("No skills extracted for chart."); fig = go.Figure(); fig.add_annotation(text="No skills extracted", showarrow=False); fig.update_layout(title="Skills"); return fig
except Exception as e: logger.exception(f"Error creating skill chart: {e}"); fig = go.Figure(); fig.add_annotation(text="Error analyzing", showarrow=False); fig.update_layout(title="Skills"); return fig
# --- Gradio Interface Components ---
def create_interface():
"""Create the Gradio interface for Aishura"""
session_user_id = str(uuid.uuid4())
logger.info(f"Initializing Gradio interface for session user ID: {session_user_id}")
get_user_profile(session_user_id) # Initialize profile
# --- Event Handlers ---
def welcome(name, location, emotion, goal):
logger.info(f"Welcome: name='{name}', loc='{location}', emo='{emotion}', goal='{goal}'")
if not all([name, location, emotion, goal]): return ("Fill all fields.", gr.update(visible=True), gr.update(visible=False))
cleaned_goal = goal.rsplit(" ", 1)[0] if goal[-1].isnumeric() == False and goal[-2] == " " else goal
update_user_profile(session_user_id, {"name": name, "location": location, "career_goal": cleaned_goal})
add_emotion_record(session_user_id, emotion)
initial_input = f"Hi Aishura! I'm {name} from {location}. I'm feeling {emotion}, and my main goal is '{cleaned_goal}'. Help me start?"
ai_response = get_ai_response(session_user_id, initial_input, generate_recommendations=True)
initial_chat = [{"role":"user", "content": initial_input}, {"role":"assistant", "content": ai_response}]
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)
# Correct Plot updates using value=
return (gr.update(value=initial_chat), 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))
def chat_submit(message_text, history_list_dicts):
logger.info(f"Chat submit: '{message_text[:50]}...'")
if not message_text: return history_list_dicts, "", gr.update()
history_list_dicts.append({"role": "user", "content": message_text})
ai_response_text = get_ai_response(session_user_id, message_text, generate_recommendations=True)
history_list_dicts.append({"role": "assistant", "content": ai_response_text})
recs_md = display_recommendations(session_user_id)
return history_list_dicts, "", gr.update(value=recs_md)
# --- Tool Interface Handlers ---
def generate_template_interface_handler(doc_type, career_field, experience):
logger.info(f"Manual Template UI: 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: 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', 'Routine')}\n\n{data.get('description', '')}\n\n"
for day in data.get('daily_tasks', []):
md += f"## Day {day.get('day', '?')}\n"
tasks = day.get('tasks', []); md += "- Rest day.\n" if not tasks else ""
for task in tasks: md += f"- **{task.get('name', 'Task')}** ({task.get('duration', '?')}m)\n *Why: {task.get('description', '...') }*\n"
md += "\n"
gauge = create_routine_completion_gauge(session_user_id)
return md, gr.update(value=gauge) # Correct Plot update
except: return "Error displaying routine.", gr.update()
def analyze_resume_interface_handler(resume_text):
logger.info(f"Manual Resume Analysis UI: len={len(resume_text)}")
if not resume_text: return "Paste resume.", gr.update(value=None)
profile = get_user_profile(session_user_id); goal = profile.get('career_goal', 'N/A')
save_user_resume(session_user_id, resume_text)
json_str = analyze_resume(resume_text, goal)
try:
analysis = json.loads(json_str).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\n**Improvements:**\n" + "\n".join([f"- {s}" for s in analysis.get('areas_for_improvement', [])]) + 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) # Correct Plot update
except: return "Error displaying analysis.", gr.update(value=None)
def analyze_portfolio_interface_handler(portfolio_url, portfolio_description):
logger.info(f"Manual Portfolio Analysis UI: url='{portfolio_url}'")
if not portfolio_description: return "Provide description."
profile = get_user_profile(session_user_id); goal = profile.get('career_goal', 'N/A')
save_user_portfolio(session_user_id, portfolio_url, portfolio_description)
json_str = analyze_portfolio(portfolio_description, goal, portfolio_url)
try:
analysis = json.loads(json_str).get('analysis', {})
md = f"## Portfolio Analysis (Simulated)\n\n**Goal:** '{goal}'\n" + (f"**URL:** {portfolio_url}\n\n" if portfolio_url else "\n") + 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: return "Error displaying analysis."
# --- Progress Tracking Handlers ---
def complete_task_handler(task_name):
logger.info(f"Complete Task UI: task='{task_name}'")
if not task_name: return ("Enter task name.", "", gr.update(), gr.update(), gr.update())
add_task_to_user(session_user_id, task_name)
db = load_user_database(); profile = db.get('users', {}).get(session_user_id)
if profile and profile.get('routine_history'):
latest = profile['routine_history'][0]; inc = random.randint(5, 15)
latest['completion'] = min(100, latest.get('completion', 0) + inc); 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)
# Correct Plot updates
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: 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
# Correct Plot update
return f"Emotion updated to '{cleaned_display}'.", gr.update(value=e_fig)
def display_recommendations(current_user_id):
logger.info(f"Display recommendations for {current_user_id}")
profile = get_user_profile(current_user_id); recs = profile.get('recommendations', [])
if not recs: return "Chat for recommendations!"
latest_recs = recs[:5]; md = "# Latest Recommendations\n\n"
if not latest_recs: return md + "No recommendations."
for i, entry in enumerate(latest_recs, 1):
rec = entry.get('recommendation', {})
md += f"### {i}. {rec.get('title', 'N/A')}\n{rec.get('description', 'N/A')}\n"
md += f"**Priority:** {rec.get('priority', 'N/A').title()} | **Type:** {rec.get('action_type', 'N/A').replace('_', ' ').title()}\n---\n"
return md
# --- Build Gradio Interface ---
with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky", secondary_hue="blue")) as app:
gr.Markdown("# Aishura - Your AI Career Assistant")
# Welcome Screen
with gr.Group(visible=True) as welcome_group:
gr.Markdown("## Welcome! Let's get started."); gr.Markdown("Tell me about yourself.")
with gr.Row():
with gr.Column(): name_input = gr.Textbox(label="Name"); location_input = gr.Textbox(label="Location")
with gr.Column(): emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling?"); goal_dropdown = gr.Dropdown(choices=GOAL_TYPES, label="What's your main goal?") # Label updated
welcome_button = gr.Button("Start My Journey"); welcome_output = gr.Markdown()
# Main Interface
with gr.Group(visible=False) as main_interface:
with gr.Tabs():
# Chat Tab
with gr.TabItem("πŸ’¬ Chat"):
with gr.Row():
with gr.Column(scale=3):
chatbot = gr.Chatbot(label="Aishura", height=550, type="messages", show_copy_button=True) # Corrected init
msg_textbox = gr.Textbox(show_label=False, placeholder="Type message...", container=False, scale=1)
with gr.Column(scale=1): gr.Markdown("### ✨ Recommendations"); recommendation_output = gr.Markdown("..."); refresh_recs_button = gr.Button("πŸ”„ Refresh")
# Analysis Tab
with gr.TabItem("πŸ“Š Analysis"):
with gr.Tabs():
with gr.TabItem("πŸ“„ Resume"): gr.Markdown("### Resume Analysis"); resume_text_input = gr.Textbox(label="Paste Resume", lines=15); analyze_resume_button = gr.Button("Analyze Resume"); resume_analysis_output = gr.Markdown()
with gr.TabItem("🎨 Portfolio"): gr.Markdown("### Portfolio Analysis"); portfolio_url_input = gr.Textbox(label="URL (Optional)"); portfolio_desc_input = gr.Textbox(label="Description", lines=5); analyze_portfolio_button = gr.Button("Analyze Portfolio"); portfolio_analysis_output = gr.Markdown()
with gr.TabItem("πŸ’‘ Skills"): gr.Markdown("### Skill Assessment"); skill_radar_chart_output = gr.Plot(label="Skills") # Corrected init
# Tools Tab (No Job Search)
with gr.TabItem("πŸ› οΈ Tools"):
with gr.Tabs():
with gr.TabItem("πŸ“ Templates"): gr.Markdown("### Docs"); doc_type_dropdown = gr.Dropdown(choices=["Resume", "Cover Letter", "LinkedIn Summary", "Networking Email"], label="Type"); doc_field_input = gr.Textbox(label="Field"); doc_exp_dropdown = gr.Dropdown(choices=["Entry", "Mid", "Senior", "Student"], label="Level"); generate_template_button = gr.Button("Generate"); template_output_md = gr.Markdown()
with gr.TabItem("πŸ“… Routine"): gr.Markdown("### Routine"); routine_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="Feeling?"); routine_goal_input = gr.Textbox(label="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"); routine_output_md = gr.Markdown()
# Progress Tab
with gr.TabItem("πŸ“ˆ Progress"):
gr.Markdown("## Track Journey")
with gr.Row():
with gr.Column(scale=1): gr.Markdown("### Task Done"); task_input = gr.Textbox(label="Task"); complete_button = gr.Button("Complete"); task_output = gr.Markdown(); gr.Markdown("---"); gr.Markdown("### Update Emotion"); new_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="Feeling now?"); emotion_button = gr.Button("Update"); emotion_output = gr.Markdown()
with gr.Column(scale=2): gr.Markdown("### Visuals"); emotion_chart_output = gr.Plot(label="Emotion") # Corrected init
with gr.Row(): progress_chart_output = gr.Plot(label="Progress") # Corrected init
with gr.Row(): routine_gauge_output = gr.Plot(label="Routine") # Corrected init
# --- Event Wiring ---
welcome_button.click( fn=welcome, inputs=[name_input, location_input, emotion_dropdown, goal_dropdown], outputs=[chatbot, welcome_group, main_interface, emotion_chart_output, progress_chart_output, routine_gauge_output, skill_radar_chart_output] )
msg_textbox.submit( fn=chat_submit, inputs=[msg_textbox, chatbot], outputs=[chatbot, msg_textbox, recommendation_output] )
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_text_input], outputs=[resume_analysis_output, skill_radar_chart_output] )
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__":
if not OPENAI_API_KEY: print("\nWarning: OPENAI_API_KEY not found.\n")
logger.info("Starting Aishura Gradio application...")
aishura_app = create_interface()
aishura_app.launch(share=False) # Set share=True for public link
logger.info("Aishura Gradio application stopped.")