Skip to content

diegobmd/aschealth

Repository files navigation

ASC Health - Medical Record Management System

A FastAPI-based application for managing patient information and medical notes with AI-powered analysis and summary generation using Google's Gemini API.

Overview

ASC Health is a comprehensive medical records system that enables healthcare providers to:

  • Manage Patients: Create, read, update, and delete patient records with demographic information
  • Store Medical Notes: Upload and store medical notes in various formats (text, documents, etc.)
  • Extract SOAP Components: Automatically extract Subjective, Objective, Assessment, and Plan (SOAP) components from medical notes using AI
  • Generate Summaries: Create AI-powered summaries of patient medical histories tailored to specific audiences
  • Track Processing Status: Monitor the status of note processing (created, success, error)

Key Features

  • 🏥 Patient Management: Full CRUD operations with filtering and sorting capabilities
  • 📝 Medical Notes: Support for multiple file formats and plain text input
  • 🤖 AI-Powered Analysis: Leverages Google's Gemini API for intelligent note extraction
  • 📊 SOAP Format Support: Automatic extraction of SOAP components from clinical notes
  • 🔍 Advanced Search: Filter patients by name and date of birth
  • 📄 Pagination: Efficient handling of large datasets
  • 📱 RESTful API: Comprehensive API with Swagger/OpenAPI documentation

Prerequisites

  • Docker and Docker Compose
  • Google Gemini API Key
  • Python 3.12+ (for local development)

Quick Start

1. Clone the Repository

git clone <repository-url>
cd aschealth

2. Set Up Environment Variables

Create a .env file in the project root with your Gemini API key:

GEMINI_API_KEY=your_gemini_api_key_here
GEMINI_MODEL=gemini-3-flash-preview
ENVIRONMENT=local

3. Run with Docker Compose

Start the entire application stack (API + PostgreSQL) with a single command:

docker-compose up -d

This will:

  • Build the FastAPI application Docker image
  • Start the PostgreSQL database
  • Initialize the database with schema and seed data
  • Expose the API on http://localhost:8000
  • Expose PostgreSQL on localhost:5432

4. Access the Swagger UI

Once the application is running, open your browser and navigate to:

http://localhost:8000/docs

You'll see the interactive Swagger UI where you can:

  • View all available endpoints
  • Test API operations directly
  • See request/response schemas
  • Try out different parameters

Alternative: ReDoc Documentation

For an alternative API documentation view, visit:

http://localhost:8000/redoc

API Endpoints

Patient Endpoints

GET /patients

Retrieve all patients with pagination, filtering, and sorting

Query Parameters:

  • offset (int): Number of records to skip (default: 0)
  • limit (int): Maximum records to return (default: 100, max: 100)
  • filter_name (string): Filter by patient name (case-insensitive)
  • filter_birth_date (date): Filter by birth date
  • sort_by (string): Sort field (id, name, birth_date)
  • descending (bool): Sort in descending order

Example:

curl "http://localhost:8000/patients?limit=10&filter_name=Diego&sort_by=name"

GET /patients/{patient_id}

Get a specific patient by ID

POST /patients

Create a new patient

Request Body:

{
  "name": "John Doe",
  "birth_date": "1990-01-15"
}

PUT /patients/{patient_id}

Update an existing patient

DELETE /patients/{patient_id}

Delete a patient

Medical Notes Endpoints

POST /patients/{patient_id}/notes

Create a new medical note for a patient

Supports:

  • File upload: multipart/form-data with file
  • Plain text: text/plain in request body

Optional Parameters:

  • noted_at (datetime): Timestamp for the note (defaults to current UTC time)

Example (Text):

curl -X POST "http://localhost:8000/patients/1/notes" \
  -H "Content-Type: text/plain" \
  -d "SOAP Note content here..."

Example (File):

curl -X POST "http://localhost:8000/patients/1/notes" \
  -F "file=@note.txt"

GET /patients/{patient_id}/notes

Retrieve all notes for a patient

DELETE /patients/notes/{note_id}

Delete a specific note

GET /patients/{patient_id}/summary

Generate an AI-powered summary of patient's medical history

Query Parameters:

  • audience (string): Target audience for the summary (e.g., "medical students", "patients")
  • verbose (bool): Generate more detailed summary

Example:

curl "http://localhost:8000/patients/1/summary?audience=medical%20students&verbose=true"

Infrastructure Endpoints

GET /

Root endpoint

Response:

ASC Health

GET /health

Health check endpoint

Response:

{
  "status": "OK"
}

GET /metrics

Prometheus metrics endpoint

Exposes application metrics in Prometheus format for monitoring and alerting.

Metrics Tracked:

  • Request count by method, path, and status code
  • Request latency/duration (histogram)
  • Request size and response size
  • HTTP exceptions

Response Format:

# HELP http_requests_total Total HTTP requests
# TYPE http_requests_total counter
http_requests_total{method="GET",path="/patients",status_code="200"} 42.0

# HELP http_request_duration_seconds HTTP request latency in seconds
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.005",method="GET",path="/patients"} 5.0
...

Example Usage with Curl:

curl http://localhost:8000/metrics

Using Swagger UI for API Testing

  1. Navigate to Swagger: Open http://localhost:8000/docs

  2. Expand an Endpoint: Click on any endpoint to expand its details

  3. Try It Out: Click the "Try it out" button

  4. Fill in Parameters: Enter required path, query, or body parameters

  5. Execute: Click "Execute" to send the request

  6. View Response: See the response status code, headers, and body

Example Workflow in Swagger

  1. Create a Patient:

    • Open POST /patients
    • Click "Try it out"
    • Enter patient data:
      {
        "name": "Jane Smith",
        "birth_date": "1985-06-20"
      }
    • Click Execute
    • Note the returned patient ID
  2. Upload a Medical Note:

    • Open POST /patients/{patient_id}/notes
    • Replace {patient_id} with the ID from step 1
    • Click "Try it out"
    • Enter note content or upload a file
    • Click Execute
  3. Generate Summary:

    • Open GET /patients/{patient_id}/summary
    • Replace {patient_id} with the patient ID
    • Optionally set audience and verbose parameters
    • Click Execute

Development

Local Setup

Install dependencies with PDM:

pdm install

Run Tests

pdm run pytest

Run Linting/Formatting

pdm run ruff check .
pdm run black .

Monitoring with Prometheus

ASC Health includes built-in Prometheus instrumentation through prometheus-fastapi-instrumentator. This automatically tracks and exposes application metrics.

Metrics Collected

The application automatically collects the following metrics:

  • HTTP Requests: Total requests by method, path, and status code
  • Request Duration: Latency distribution (histogram) for all endpoints
  • Request/Response Size: Request and response body sizes
  • HTTP Exceptions: Tracking of errors and exceptions

Accessing Metrics

Prometheus metrics are exposed at the /metrics endpoint:

curl http://localhost:8000/metrics

Setting Up Prometheus Server (Optional)

To scrape and visualize metrics, you can run Prometheus alongside ASC Health.

Add to docker-compose.yml:

prometheus:
  image: prom/prometheus:latest
  ports:
    - "9090:9090"
  volumes:
    - ./prometheus.yml:/etc/prometheus/prometheus.yml
  command:
    - '--config.file=/etc/prometheus/prometheus.yml'

Create prometheus.yml:

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'aschealth'
    static_configs:
      - targets: ['localhost:8000']
    metrics_path: '/metrics'

Viewing Prometheus Dashboard

Once Prometheus is running, access the dashboard at:

http://localhost:9090

Example Queries:

# Total requests per endpoint
rate(http_requests_total[5m])

# Average request duration per endpoint
rate(http_request_duration_seconds_sum[5m]) / rate(http_requests_total[5m])

# Error rate
rate(http_requests_total{status_code=~"5.."}[5m])

# Requests per second
rate(http_requests_total[1m])

Integrating with Grafana (Optional)

For advanced visualization, connect Prometheus as a data source to Grafana:

  1. Add Prometheus data source: http://prometheus:9090
  2. Create dashboards to visualize:
    • Request rates and latency
    • Error rates
    • API endpoint performance
    • System health metrics

Development

Local Setup

Install dependencies with PDM:

pdm install

Run Tests

pdm run pytest

Run Linting/Formatting

pdm run ruff check .
pdm run black .

Project Structure

aschealth/
├── controllers/          # API endpoint handlers
│   ├── infra.py         # Health check endpoints
│   └── patients.py      # Patient and note management
├── model/               # Database models
│   ├── patient.py       # Patient entity
│   └── note.py          # Medical note entity
├── dtos/                # Data transfer objects
│   ├── patient.py       # Patient request/response models
│   ├── note.py          # Note request/response models
│   └── infra.py         # Infrastructure models
├── dependencies/        # Dependency injection
│   ├── api.py           # API dependencies (GenAI client)
│   └── datasource.py    # Database dependencies
├── config.py            # Application configuration
└── main.py              # FastAPI app initialization

init_db/
├── schema.sql           # Database schema
└── seed.sql             # Sample data

tests/
├── controllers/         # API endpoint tests
├── test_factories/      # Test data factories
└── conftest.py          # Pytest configuration

Troubleshooting

Container won't start

Check Docker logs:

docker-compose logs api
docker-compose logs postgres

Permission denied errors

Ensure postgres-data directory has correct permissions:

chmod -R 755 postgres-data/

Database connection errors

Verify the database is running:

docker-compose ps

If needed, restart the services:

docker-compose down
docker-compose up -d

Gemini API errors

Verify your API key:

  • Check .env file has correct key format
  • Ensure API is enabled in Google Cloud Console
  • Verify account has sufficient quota

Environment Variables

Variable Description Default
GEMINI_API_KEY Google Gemini API Key Required
GEMINI_MODEL Gemini model to use gemini-3-flash-preview
ENVIRONMENT Deployment environment local
DATABASE_DSN PostgreSQL connection string Auto-configured

API Response Examples

Create Patient Response (201)

{
  "id": 1,
  "name": "John Doe",
  "birth_date": "1990-01-15"
}

Get Patients Response (200)

{
  "total": 5,
  "items": [
    {
      "id": 1,
      "name": "John Doe",
      "birth_date": "1990-01-15"
    }
  ]
}

Create Note Response (201)

{
  "id": 1,
  "patient_id": 1,
  "status": "CREATED",
  "noted_at_utc": "2024-01-15T10:30:00",
  "note": null,
  "subjective": null,
  "objective": null,
  "assessment": null,
  "plan": null
}

Patient Summary Response (200)

{
  "id": 1,
  "name": "John Doe",
  "birth_date": "1990-01-15",
  "summary": "Patient has a history of hypertension and is currently on statin therapy..."
}

Docker Commands

View logs

docker-compose logs -f api
docker-compose logs -f postgres

Stop services

docker-compose down

Remove all data

docker-compose down -v

Restart services

docker-compose restart

Database Access

Access PostgreSQL directly (if needed):

docker-compose exec postgres psql -U aschealth -d aschealth

Common commands:

-- List all patients
SELECT * FROM patient;

-- List all notes
SELECT * FROM note;

-- Get notes for a specific patient
SELECT * FROM note WHERE patient_id = 1;

Contributing

When contributing to ASC Health:

  1. Add comprehensive docstrings to all functions and classes
  2. Include unit tests for new features
  3. Update this README with any new endpoints or features
  4. Follow the existing code style and structure

License

This project is part of the ASC Health system.

Support

For issues or questions, please check the Docker logs and verify your environment setup:

docker-compose logs

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published