Skip to content

Grief Compass is an AI-powered FastAPI platform for personalized grief counseling and emotional support, offering empathetic sentiment analysis, tailored daily routines, and customized motivational content to guide individuals through their healing journey.

Notifications You must be signed in to change notification settings

Nazmul0005/Grief-Compass

Repository files navigation

Grief Compass

FastAPI Python Docker Pydantic Nginx License Status

An AI-powered platform for personalized grief counseling and support, providing compassionate assistance through intelligent tools and personalized content.

Project Screenshot

🌟 Overview

Grief Compass is a comprehensive FastAPI-based application that leverages advanced AI models to provide personalized grief counseling services. The platform offers three core services designed to support individuals through their grief journey with empathy and understanding.

✨ Features

1. Sentiment Analysis Toolkit (/api/v1/sentiment-analyze)

  • Analyzes grief-related thoughts and emotions
  • Identifies emotional states (Happy, Sad, Angry, Numb, Confused)
  • Provides personalized tool recommendations across six categories:
    • Stay Connected
    • Work Through Emotions
    • Find Strength
    • Mindfulness
    • Check In
    • Get Moving
  • Context-aware suggestions based on relationship type and cause of loss

2. Daily Schedule Builder (/api/v1/daily-schedule)

  • Generates personalized daily schedules tailored to grief context
  • Creates 4-5 specific activities for each time period (morning, noon, afternoon, evening, night)
  • Includes:
    • Physical activities with exact movements and duration
    • Detailed meal suggestions with specific foods
    • Grief rituals with specific prompts and themes
    • Supportive activities with step-by-step instructions
  • All activities are actionable and personalized to the user's loss and emotional state

3. Personalized Content Generator (/api/v1/personalized-content)

  • Creates customized grief support content including:
    • Motivation Cards: Uplifting messages tailored to the user's situation
    • Song Recommendations: Curated music with YouTube links and personalized reasoning
    • Essays: Multi-section written content (Introduction, Body, Conclusion) with word count management
  • Integrates web search for accurate song recommendations via Tavily API
  • Content personalized based on relationship type, cause of loss, and selected tool category

🏗️ Architecture

Project Structure

Grief-Compass/
├── com/
│   └── mhire/
│       └── app/
│           ├── main.py                 # FastAPI application entry point
│           ├── config/
│           │   └── config.py           # Configuration management (Singleton pattern)
│           ├── common/
│           │   ├── exceptions_utility.py    # Exception handling utilities
│           │   ├── json_handler.py          # LLM JSON parsing and validation
│           │   └── network_responses.py     # Standardized API responses
│           └── services/
│               ├── sentiment_toolkit/
│               │   ├── sentiment_toolkit.py
│               │   ├── sentiment_toolkit_router.py
│               │   └── sentiment_toolkit_schema.py
│               ├── schedule_builder/
│               │   ├── schedule_builder.py
│               │   ├── schedule_builder_router.py
│               │   └── schedule_builder_schema.py
│               └── personalized_content/
│                   ├── personalized_content.py
│                   ├── personalized_content_router.py
│                   └── personalized_content_schema.py
├── nginx/
│   └── nginx.conf                  # Nginx reverse proxy configuration
├── Dockerfile                      # Docker container configuration
├── docker-compose.yml              # Multi-container orchestration
├── gunicorn_config.py             # Gunicorn WSGI server configuration
├── requirements.txt                # Python dependencies
└── README.md                       # Project documentation

Technology Stack

  • Framework: FastAPI (Python 3.10+)
  • AI Models: Groq API (LLM integration)
  • Web Search: Tavily API (for song recommendations)
  • Validation: Pydantic v2
  • Server: Gunicorn with Uvicorn workers
  • Reverse Proxy: Nginx
  • Containerization: Docker & Docker Compose

🚀 Getting Started

Prerequisites

  • Python 3.10 or higher
  • Docker and Docker Compose (for containerized deployment)
  • API Keys:
    • Groq API Key
    • Tavily API Key

Environment Variables

Create a .env file in the project root with the following variables:

GROQ_API_KEY=your_groq_api_key_here
GROQ_MODEL_NAME=your_model_name_here
TAVILY_API_KEY=your_tavily_api_key_here

Local Development

  1. Clone the repository

    git clone <repository-url>
    cd Grief-Compass
  2. Install dependencies

    pip install -r requirements.txt
  3. Run the application

    uvicorn com.mhire.app.main:app --reload --host 0.0.0.0 --port 8000
  4. Access the API

    • API Base URL: http://localhost:8000
    • Interactive Docs: http://localhost:8000/docs
    • Health Check: http://localhost:8000/health

Docker Deployment

  1. Build and run with Docker Compose

    docker-compose up -d
  2. Access the application

    • The application will be available at http://localhost:5004
    • Nginx acts as a reverse proxy to the FastAPI application
  3. View logs

    docker-compose logs -f
  4. Stop the application

    docker-compose down

📡 API Endpoints

Health Check

GET /health

Returns the health status of the application.

Root Endpoint

GET /

Returns basic application information.

Sentiment Analysis

POST /api/v1/sentiment-analyze
Content-Type: application/json

{
  "user_thoughts": "I'm struggling to cope with the loss",
  "relationship": "Parent",
  "cause_of_loss": "Illness"
}

Response:

{
  "success": true,
  "message": "Response generated successfully.",
  "data": {
    "mood": "Sad",
    "titles": {
      "1. Stay Connected": {
        "description": "...",
        "tools": ["tool1", "tool2"]
      },
      ...
    }
  },
  "resource": "/api/v1/sentiment-analyze",
  "duration": "2.5s"
}

Daily Schedule

POST /api/v1/daily-schedule
Content-Type: application/json

{
  "user_thoughts": "I need structure in my day",
  "relationship": "Partner",
  "cause_of_loss": "Accident"
}

Response:

{
  "success": true,
  "message": "Response generated successfully.",
  "data": {
    "date": "2025-12-13",
    "morning": [
      {
        "time_frame": "7:00 AM - 7:30 AM",
        "activity": "Morning Mindfulness",
        "description": "Detailed step-by-step instructions..."
      },
      ...
    ],
    "noon": [...],
    "afternoon": [...],
    "evening": [...],
    "night": [...]
  },
  "resource": "/api/v1/daily-schedule",
  "duration": "3.2s"
}

Personalized Content

POST /api/v1/personalized-content
Content-Type: application/json

{
  "user_thoughts": "I want to find strength",
  "relationship": "Sibling",
  "cause_of_loss": "Natural",
  "tool_title": "Find Strength",
  "tool_description": "Activities to build resilience",
  "tool_name": "Resilience Building Exercise"
}

Response:

{
  "success": true,
  "message": "Response generated successfully.",
  "data": {
    "motivation_cards": [
      "Card 1 message...",
      "Card 2 message...",
      "Card 3 message..."
    ],
    "song_recommendation": {
      "title": "Song Title",
      "url": "https://youtube.com/...",
      "reason": "Why this song is recommended..."
    },
    "essay": {
      "introduction": "Essay introduction...",
      "body": "Essay body...",
      "conclusion": "Essay conclusion..."
    }
  },
  "resource": "/api/v1/personalized-content",
  "duration": "5.8s"
}

🔧 Configuration

Gunicorn Configuration

The application uses Gunicorn with Uvicorn workers for production deployment:

  • Workers: 4
  • Worker Class: uvicorn.workers.UvicornWorker
  • Bind Address: 0.0.0.0:8000

Nginx Configuration

  • Port Mapping: 5004:80
  • Client Max Body Size: 25M
  • Proxy Read Timeout: 1000s (for external API calls)
  • Gzip Compression: Enabled

🛡️ Error Handling

The application implements comprehensive error handling:

  • Validation Errors: Pydantic model validation with detailed error messages
  • HTTP Exceptions: Custom exception handling with proper status codes
  • LLM Response Parsing: Retry logic with JSON cleaning and validation
  • Standardized Responses: Consistent error response format across all endpoints

Error Response Format

{
  "code": 422,
  "success": false,
  "error": {
    "code": 42202,
    "message": "Error processing grief content."
  },
  "resource": "/api/v1/sentiment-analyze",
  "duration": "1.2s"
}

📊 Data Models

Enumerations

Relationship Types:

  • Parent
  • Child
  • Sibling
  • Partner
  • Friend
  • Other

Cause of Loss:

  • Illness
  • Accident
  • Suicide
  • Natural
  • Murder
  • Other

Emotions:

  • Happy
  • Sad
  • Angry
  • Numb
  • Confused

Tool Categories:

  • Stay Connected
  • Work Through Emotions
  • Find Strength
  • Mindfulness
  • Check In
  • Get Moving

🔒 Security Features

  • CORS: Configured for cross-origin requests (configure specific origins in production)
  • Server Tokens: Disabled in Nginx for security
  • Environment Variables: Sensitive data stored in .env file (not committed to version control)
  • Input Validation: Pydantic models ensure type safety and data validation

📝 Logging

The application uses Python's built-in logging module with:

  • Level: INFO
  • Format: %(asctime)s - %(levelname)s - %(name)s - %(message)s
  • Output: Console (StreamHandler)

🤝 Contributing

This is a grief counseling platform designed with empathy and care. When contributing:

  1. Maintain the compassionate tone in all AI-generated content
  2. Ensure proper error handling for user-facing features
  3. Test all endpoints thoroughly
  4. Follow the existing code structure and patterns
  5. Update documentation for any new features

📄 License

[Add your license information here]

🙏 Acknowledgments

This platform is built to support individuals through their grief journey with compassion, understanding, and AI-powered personalization.

📞 Support

For issues, questions, or suggestions, please create an issue or contact the development team.


Note: This application handles sensitive emotional content. Always ensure proper data privacy and security measures are in place when deploying to production.

About

Grief Compass is an AI-powered FastAPI platform for personalized grief counseling and emotional support, offering empathetic sentiment analysis, tailored daily routines, and customized motivational content to guide individuals through their healing journey.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published