# Main Components of OpenMed: A Modular Architecture for Medical NLP

> Discover the main components of OpenMed: its six modular layers (Core, Processing, NER Families, Privacy & PII, Utilities, Service/API) form a powerful clinical text analysis framework.

- Repository: [Maziyar Panahi/openmed](https://github.com/maziyarpanahi/openmed)
- Tags: architecture
- Published: 2026-06-13

---

**OpenMed is organized into six modular layers—Core, Processing, NER Families, Privacy & PII, Utilities, and Service/API—that together provide a plug-and-play framework for clinical text analysis.**

The `maziyarpanahi/openmed` repository delivers a Python-based toolkit for medical-domain NLP tasks. Understanding the main components of OpenMed helps developers integrate clinical entity recognition, privacy-preserving text processing, and model management into healthcare applications.

## Core Architecture Components

### Configuration and Model Management

The foundation resides in `openmed/core/`. The `OpenMedConfig` class in [`openmed/core/config.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/config.py) handles global defaults via environment variables or TOML files. The [`model_registry.py`](https://github.com/maziyarpanahi/openmed/blob/main/model_registry.py) file loads the static `models.jsonl` manifest, while [`openmed/core/models.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/models.py) implements the `ModelLoader` class responsible for fetching Hugging Face or local models, building pipelines, and managing caching.

### Text Processing Layer

Located in `openmed/processing/`, this layer handles tokenization and output formatting. The `TextProcessor` class in [`openmed/processing/text.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/processing/text.py) manages tokenization and sentence segmentation, supported by [`openmed/processing/sentences.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/processing/sentences.py) for detection utilities. Final output generation occurs in [`openmed/processing/outputs.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/processing/outputs.py) through functions like `format_predictions`, supporting JSON, dict, HTML, and CSV formats.

### NER Back-End Families

The `openmed/ner/families/` directory abstracts different zero-shot or fine-tuned NER implementations. The [`base.py`](https://github.com/maziyarpanahi/openmed/blob/main/base.py) module defines the common interface, while [`openmed/ner/families/gliner.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/ner/families/gliner.py) provides a thin wrapper around the GLiNER zero-shot NER library. Each family supplies wrappers that know how to load models and run inference, enabling seamless backend swapping.

### Privacy and PII Protection

Medical privacy functions live in [`openmed/core/pii.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/pii.py) and [`openmed/core/pii_i18n.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/pii_i18n.py). These modules implement de-identification, PII extraction, and language-specific pattern matching. The internationalization support in [`pii_i18n.py`](https://github.com/maziyarpanahi/openmed/blob/main/pii_i18n.py) enables multilingual PII detection across diverse clinical corpora.

### Risk Assessment and MLX Acceleration

Optional specialized components include re-identification risk assessment in [`openmed/risk/reid.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/risk/reid.py) and Apple MLX on-device inference support in `openmed/mlx/models/`. These extend OpenMed's capabilities for privacy risk scoring and Apple Silicon optimization.

### Service and API Layer

The FastAPI-based web service in [`openmed/service/app.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/service/app.py) exposes core inference functions as HTTP endpoints. This lightweight service layer provides routes for `list_models`, `analyze_text`, and other public API functions, enabling RESTful integration.

## Data Flow and Usage Patterns

The typical execution flow traverses these main components of OpenMed in five stages:

1. **Load configuration**: Initialize `OpenMedConfig` with global defaults overridden via environment variables or TOML files.
2. **Create ModelLoader**: Resolve model names (registry keys, Hugging Face repo IDs, or local paths) using the `ModelLoader` class from [`openmed/core/models.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/models.py).
3. **Build pipeline**: Call `ModelLoader.create_pipeline()` to return a Hugging Face `pipeline` object or backend-specific pipeline.
4. **Run inference**: Execute `analyze_text()` for high-level processing, which handles sentence segmentation, max-length truncation, and prediction formatting.
5. **Post-process**: Apply confidence threshold filtering, entity grouping, and medical-aware token remapping to generate final outputs.

## Public API and Entry Points

All components wire together through [`openmed/__init__.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/__init__.py), exposing a concise public API:

```python
from openmed import (
    list_models,
    get_model_max_length,
    analyze_text,
    ModelLoader,
    load_model,
    OpenMedConfig,
)

```

**Listing Available Models**

Query the model registry to discover supported clinical models:

```python
from openmed import list_models

print("Available models:", list_models())

```

**High-Level Text Analysis**

Process clinical text with automatic entity detection:

```python
from openmed import analyze_text

text = "Patient reports shortness of breath and elevated troponin levels."
result = analyze_text(
    text,
    model_name="disease_detection_superclinical",
    aggregation_strategy="simple",
    output_format="json",
    confidence_threshold=0.6,
)

print(result)  # JSON string with detected entities

```

**Low-Level Pipeline Control**

For custom processing, use the `ModelLoader` directly:

```python
from openmed import ModelLoader

loader = ModelLoader()
pipeline = loader.create_pipeline(
    "pharma_detection_superclinical",
    task="token-classification",
    aggregation_strategy="average",
)

preds = pipeline("The patient was prescribed 500 mg of amoxicillin.")
print(preds)

```

## Summary

- **Core Layer**: `openmed/core/` contains configuration, model registry, and the `ModelLoader` for managing Hugging Face and local models.
- **Processing Layer**: `openmed/processing/` handles tokenization, sentence segmentation, and output formatting.
- **NER Families**: `openmed/ner/families/` provides abstracted wrappers for GLiNER and other back-end implementations.
- **Privacy Components**: [`openmed/core/pii.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/pii.py) and [`pii_i18n.py`](https://github.com/maziyarpanahi/openmed/blob/main/pii_i18n.py) manage de-identification and multilingual PII extraction.
- **Utilities**: `openmed/utils/` provides validation, profiling, and logging helpers.
- **Service Layer**: [`openmed/service/app.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/service/app.py) exposes FastAPI endpoints for RESTful integration.
- **MLX Support**: `openmed/mlx/models/` enables Apple Silicon on-device inference.

## Frequently Asked Questions

### What is the role of ModelLoader in OpenMed?

The `ModelLoader` class in [`openmed/core/models.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/models.py) serves as the central model management component. It resolves model names against the registry, fetches weights from Hugging Face or local paths, and constructs inference pipelines. This abstraction allows users to switch between different clinical models without modifying application code.

### How does OpenMed handle patient privacy and PII?

OpenMed implements privacy-preserving utilities in [`openmed/core/pii.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/pii.py) and [`openmed/core/pii_i18n.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/core/pii_i18n.py). These modules extract and de-identify personally identifiable information using language-specific patterns. The framework supports multilingual PII detection and can be extended with custom regex patterns for specific clinical domains.

### Can OpenMed run on Apple Silicon hardware?

Yes, OpenMed includes optional MLX support through `openmed/mlx/models/` for Apple Silicon on-device inference. Additionally, the [`openmed/risk/reid.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/risk/reid.py) module provides re-identification risk assessment utilities. These components allow deployment on macOS devices without requiring cloud-based GPU resources.

### What output formats does OpenMed support?

According to [`openmed/processing/outputs.py`](https://github.com/maziyarpanahi/openmed/blob/main/openmed/processing/outputs.py), OpenMed supports multiple output formats including JSON, Python dictionaries, HTML, and CSV. The `format_predictions` function handles conversion from raw model outputs to these formats, with optional confidence threshold filtering and entity aggregation strategies.