# maziyarpanahi/openmed architecture

> Architecture diagram of the GitHub repository maziyarpanahi/openmed, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-25). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/maziyarpanahi/openmed
- Repository: https://github.com/maziyarpanahi/openmed

## Overview

1. **Repository structure**
   This is a multi-language monorepo centered on a Python medical NLP library, with adjacent Swift runtime support, demo apps, docs, and tests. The main production surface is `openmed/`; the Swift package lives under `swift/OpenMedKit/`, and the Python service layer is `openmed/service/`.

2. **Primary Python API boundary**
   The user-facing entry points are the high-level helpers exposed by `openmed` such as `analyze_text`, `extract_pii`, `deidentify`, and `BatchProcessor`. These APIs hide model loading, backend selection, preprocessing, inference, and output formatting behind a single call surface.

3. **Model registry and runtime routing**
   A central model registry maps model names/IDs to metadata, labels, and supported families. The `openmed/core` and `openmed/ner` layers determine which backend to use based on the model family and environment, so the same API can target Hugging Face/Transformers-style models, MLX artifacts, CoreML packages, or Torch-based privacy-filter models.

4. **Text-to-entities pipeline**
   The core NER flow is: raw clinical text → tokenization and sentence/text segmentation → model inference → decoding of spans and labels → post-processing and confidence/entity filtering. Supporting modules such as `processing/`, `core/decoding/`, `ner/`, and label maps provide the alignment and span logic needed for clinical text, where token boundaries and entity fragments matter.

5. **PII extraction and de-identification subsystem**
   PII is a distinct pipeline on top of NER. Extraction produces structured entities, while de-identification uses the extracted spans plus the anonymizer engine to mask, remove, replace, hash, or date-shift sensitive content. This subsystem includes smart merging for fragmented spans, locale-aware replacements, and clinical identifier providers for format-preserving surrogate generation.

6. **Internationalization and domain-specific rules**
   The repository treats multilingual and medical-specific behavior as first-class concerns. Language-specific label maps, PII i18n helpers, and locale/provider registries make the same anonymization flow work across multiple languages and identifier formats, instead of hard-coding English-only assumptions.

7. **Output, validation, and quality boundaries**
   Once inference completes, results are normalized into consistent output structures and can be rendered as dict/JSON/HTML/CSV-like formats depending on the caller. Validation and quality-gate modules sit around the pipeline to catch malformed inputs, unsupported configurations, or low-quality outputs before they propagate downstream.

8. **Batch and profiling utilities**
   Batch processing is a separate orchestration layer for multi-text or multi-file workflows. It reuses the same core inference pipeline but adds progress tracking, aggregation, and configurable thresholds. Profiling and logging utilities provide timing and bottleneck visibility without changing the model logic.

9. **REST service deployment path**
   `openmed.service` wraps the same core APIs behind a FastAPI server with health checks, analysis endpoints, and PII-specific endpoints. The service layer adds request/response schemas, shared model preload, runtime management, and a consistent error envelope for production deployments.

10. **MLX and Apple Silicon path**
   The `openmed/mlx/` subtree contains the Apple Silicon runtime, artifact format, conversion tooling, and MLX-native model implementations. This is the acceleration path for supported model families on macOS/iOS-class hardware, and it is intentionally parallel to the Hugging Face/Torch path rather than replacing it.

11. **CoreML and Swift integration**
   `openmed/coreml/` handles CoreML export, while the Swift package `OpenMedKit` consumes OpenMed model artifacts on Apple platforms. OpenMedKit mirrors the Python-side model selection and post-processing concepts so Swift apps can run the same model families natively in macOS/iOS contexts, either via MLX or bundled CoreML assets.

12. **Demo apps and example surfaces**
   The `swift/OpenMedDemo` and `swift/OpenMedScanDemo` apps, plus the Python examples and notebooks, are reference integrations rather than core infrastructure. They show how the same model/runtime stack can be embedded in interactive UIs, document workflows, or notebook-based experimentation.

13. **External model distribution and portability**
   The project depends heavily on external model distribution through Hugging Face-style repositories and local model directories, with optional fallbacks depending on runtime availability. This means the architecture is designed around portable artifacts and runtime substitution, not around a single fixed deployment target.

14. **Testing, CI, and release pipeline**
   The test suite is split across unit, integration, MLX, CoreML, service, and NER-specific checks, reflecting the repo’s multiple execution paths. GitHub Actions workflows cover Python tests, Swift tests, MLX validation, model conversion, publishing, and releases, which is important because correctness depends on keeping all backend variants aligned.

Main entry points: [`openmed/__init__.py`](https://github.com/maziyarpanahi/openmed/blob/master/openmed/__init__.py) (OpenMed API), [`tests/unit/test_core.py`](https://github.com/maziyarpanahi/openmed/blob/master/tests/unit/test_core.py) (Test suites), [`swift/OpenMedKit/Sources/OpenMedKit/OpenMedKit.swift`](https://github.com/maziyarpanahi/openmed/blob/master/swift/OpenMedKit/Sources/OpenMedKit/OpenMedKit.swift) (OpenMedKit), [`openmed/mlx/inference.py`](https://github.com/maziyarpanahi/openmed/blob/master/openmed/mlx/inference.py) (MLX stack)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_python["Python library"]
  node_api["OpenMed API<br/>public API<br/>[__init__.py]"]
  node_registry[("Model registry<br/>catalog<br/>[model_registry.py]")]
  node_config["Config and backends<br/>routing<br/>[config.py]"]
  node_proc["Text processing<br/>preprocess<br/>[text.py]"]
  node_sentences["Sentence split<br/>segmentation<br/>[sentences.py]"]
  node_infer["NER inference<br/>[infer.py]"]
  node_families["Model families<br/>runtime adapters<br/>[base.py]"]
  node_decoding["Span decoding<br/>postprocess<br/>[spans.py]"]
  node_outputs["Output formats<br/>serialization<br/>[outputs.py]"]
  node_pii["PII pipeline<br/>de-identification<br/>[pii.py]"]
  node_anonymizer["Anonymizer<br/>masking engine<br/>[engine.py]"]
  node_i18n["PII rules<br/>localization<br/>[pii_i18n.py]"]
  node_quality["Quality gates<br/>validation<br/>[quality_gates.py]"]
  node_batch["Batch processor<br/>orchestration<br/>[batch.py]"]
  node_profile["Profiling tools<br/>observability<br/>[profiling.py]"]
end

subgraph group_runtime["Runtime backends"]
  node_mlx["MLX stack<br/>apple runtime<br/>[inference.py]"]
  node_coreml["CoreML export<br/>[convert.py]"]
  node_torch["Privacy filter<br/>torch backend<br/>[privacy_filter.py]"]
end

subgraph group_service["REST service"]
  node_service_app["FastAPI app<br/>http service<br/>[app.py]"]
  node_service_rt["Service runtime<br/>runtime manager<br/>[runtime.py]"]
  node_service_schemas["API schemas<br/>[schemas.py]"]
end

subgraph group_swift["Swift package"]
  node_kit["OpenMedKit<br/>swift package<br/>[OpenMedKit.swift]"]
  node_demo["Swift demo<br/>[ContentView.swift]"]
end

subgraph group_tooling["Tooling and docs"]
  node_examples["Examples<br/>reference integrations"]
  node_docs["Docs site<br/>documentation<br/>[index.md]"]
  node_tests["Test suites<br/>verification<br/>[test_core.py]"]
end

node_api -->|"resolve model"| node_registry
node_api -->|"select backend"| node_config
node_api -->|"preprocess"| node_proc
node_proc -->|"segment"| node_sentences
node_proc -->|"feed text"| node_infer
node_registry -->|"family map"| node_families
node_config -->|"route mlx"| node_mlx
node_config -->|"route coreml"| node_coreml
node_config -->|"route torch"| node_torch
node_infer -->|"load adapter"| node_families
node_infer -->|"decode spans"| node_decoding
node_decoding -->|"normalize"| node_outputs
node_api -->|"PII flow"| node_pii
node_pii -->|"mask content"| node_anonymizer
node_pii -->|"locale rules"| node_i18n
node_pii -->|"gate output"| node_quality
node_batch -->|"reuse pipeline"| node_proc
node_batch -->|"multi-text infer"| node_infer
node_profile -->|"measure batches"| node_batch
node_service_app -->|"serve requests"| node_service_rt
node_service_app -->|"validate payloads"| node_service_schemas
node_service_rt -->|"call core API"| node_api
node_mlx -->|"mlx models"| node_families
node_mlx -->|"artifact lookup"| node_registry
node_coreml -->|"export models"| node_registry
node_kit -->|"consume artifacts"| node_mlx
node_kit -->|"load coreml"| node_coreml
node_kit -->|"post-process"| node_outputs
node_demo -->|"use runtime"| node_kit
node_docs -->|"document"| node_api
node_docs -->|"document"| node_service_app
node_tests -->|"verify"| node_api
node_tests -->|"verify"| node_mlx
node_tests -->|"verify"| node_coreml
node_tests -->|"verify"| node_service_app
node_tests -->|"verify"| node_kit

click node_api "https://github.com/maziyarpanahi/openmed/blob/master/openmed/__init__.py"
click node_registry "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/model_registry.py"
click node_config "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/config.py"
click node_proc "https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/text.py"
click node_sentences "https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/sentences.py"
click node_infer "https://github.com/maziyarpanahi/openmed/blob/master/openmed/ner/infer.py"
click node_families "https://github.com/maziyarpanahi/openmed/blob/master/openmed/ner/families/base.py"
click node_decoding "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/decoding/spans.py"
click node_outputs "https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/outputs.py"
click node_pii "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/pii.py"
click node_anonymizer "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/anonymizer/engine.py"
click node_i18n "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/pii_i18n.py"
click node_quality "https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/quality_gates.py"
click node_batch "https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/batch.py"
click node_profile "https://github.com/maziyarpanahi/openmed/blob/master/openmed/utils/profiling.py"
click node_service_app "https://github.com/maziyarpanahi/openmed/blob/master/openmed/service/app.py"
click node_service_rt "https://github.com/maziyarpanahi/openmed/blob/master/openmed/service/runtime.py"
click node_service_schemas "https://github.com/maziyarpanahi/openmed/blob/master/openmed/service/schemas.py"
click node_mlx "https://github.com/maziyarpanahi/openmed/blob/master/openmed/mlx/inference.py"
click node_coreml "https://github.com/maziyarpanahi/openmed/blob/master/openmed/coreml/convert.py"
click node_torch "https://github.com/maziyarpanahi/openmed/blob/master/openmed/torch/privacy_filter.py"
click node_kit "https://github.com/maziyarpanahi/openmed/blob/master/swift/OpenMedKit/Sources/OpenMedKit/OpenMedKit.swift"
click node_demo "https://github.com/maziyarpanahi/openmed/blob/master/swift/OpenMedScanDemo/OpenMedScanDemo/ContentView.swift"
click node_examples "https://github.com/maziyarpanahi/openmed/blob/master/examples/obfuscation_demo.py"
click node_docs "https://github.com/maziyarpanahi/openmed/blob/master/docs/index.md"
click node_tests "https://github.com/maziyarpanahi/openmed/blob/master/tests/unit/test_core.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_api,node_registry,node_config,node_proc,node_sentences,node_infer,node_families,node_decoding,node_outputs,node_pii,node_anonymizer,node_i18n,node_quality,node_batch,node_profile toneBlue
class node_mlx,node_coreml,node_torch toneAmber
class node_service_app,node_service_rt,node_service_schemas toneMint
class node_kit,node_demo toneRose
class node_examples,node_docs,node_tests toneIndigo
```

## Components

### Python library

Primary medical NLP and de-identification stack.

- [OpenMed API](https://github.com/maziyarpanahi/openmed/blob/master/openmed/__init__.py): public API · High-level entry points such as analyze_text, extract_pii, deidentify, and batch processing. · `openmed/__init__.py`
- [Model registry](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/model_registry.py): catalog · Maps model names and families to metadata and supported runtimes. · `openmed/core/model_registry.py`
- [Config and backends](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/config.py): routing · Resolves environment, backend selection, and runtime configuration. · `openmed/core/config.py`
- [Text processing](https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/text.py): preprocess · Tokenization, sentence splitting, and text normalization before inference. · `openmed/processing/text.py`
- [Sentence split](https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/sentences.py): segmentation · Sentence and document segmentation used by batch and NER pipelines. · `openmed/processing/sentences.py`
- [NER inference](https://github.com/maziyarpanahi/openmed/blob/master/openmed/ner/infer.py): inference · Adapter and inference layer for family-specific model execution. · `openmed/ner/infer.py`
- [Model families](https://github.com/maziyarpanahi/openmed/blob/master/openmed/ner/families/base.py): runtime adapters · Family-specific loaders and adapters for GLiNER-style and related NER models. · `openmed/ner/families/base.py`
- [Span decoding](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/decoding/spans.py): postprocess · Converts token-level outputs into entity spans and labels. · `openmed/core/decoding/spans.py`
- [Output formats](https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/outputs.py): serialization · Normalizes results into dict, JSON, HTML, and CSV-like representations. · `openmed/processing/outputs.py`
- [PII pipeline](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/pii.py): de-identification · PII extraction and masking flow built on top of NER spans. · `openmed/core/pii.py`
- [Anonymizer](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/anonymizer/engine.py): masking engine · Performs redact, replace, hash, date-shift, and locale-aware substitutions. · `openmed/core/anonymizer/engine.py`
- [PII rules](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/pii_i18n.py): localization · Language and locale registries for multilingual PII handling. · `openmed/core/pii_i18n.py`
- [Quality gates](https://github.com/maziyarpanahi/openmed/blob/master/openmed/core/quality_gates.py): validation · Checks malformed inputs, unsupported configurations, and output quality. · `openmed/core/quality_gates.py`
- [Batch processor](https://github.com/maziyarpanahi/openmed/blob/master/openmed/processing/batch.py): orchestration · Coordinates multi-text workflows with aggregation and thresholds. · `openmed/processing/batch.py`
- [Profiling tools](https://github.com/maziyarpanahi/openmed/blob/master/openmed/utils/profiling.py): observability · Timing and bottleneck visibility without changing model logic. · `openmed/utils/profiling.py`

### Runtime backends

Alternative execution paths for model inference and export.

- [MLX stack](https://github.com/maziyarpanahi/openmed/blob/master/openmed/mlx/inference.py): apple runtime · MLX artifact, conversion, inference, and native model implementations. · `openmed/mlx/inference.py`
- [CoreML export](https://github.com/maziyarpanahi/openmed/blob/master/openmed/coreml/convert.py): export · Exports supported models into CoreML artifacts for Apple platforms. · `openmed/coreml/convert.py`
- [Privacy filter](https://github.com/maziyarpanahi/openmed/blob/master/openmed/torch/privacy_filter.py): torch backend · Torch-based privacy filter implementation for supported models. · `openmed/torch/privacy_filter.py`

### REST service

Deployment layer exposing the Python APIs over HTTP.

- [FastAPI app](https://github.com/maziyarpanahi/openmed/blob/master/openmed/service/app.py): http service · REST service entry point with health and analysis endpoints. · `openmed/service/app.py`
- [Service runtime](https://github.com/maziyarpanahi/openmed/blob/master/openmed/service/runtime.py): runtime manager · Shared model preload, request lifecycle, and error envelopes. · `openmed/service/runtime.py`
- [API schemas](https://github.com/maziyarpanahi/openmed/blob/master/openmed/service/schemas.py): schemas · Request and response schemas for the service boundary. · `openmed/service/schemas.py`

### Swift package

Apple-platform runtime and demos.

- [OpenMedKit](https://github.com/maziyarpanahi/openmed/blob/master/swift/OpenMedKit/Sources/OpenMedKit/OpenMedKit.swift): swift package · Swift-side model store, pipelines, and post-processing for Apple apps. · `swift/OpenMedKit/Sources/OpenMedKit/OpenMedKit.swift`
- [Swift demo](https://github.com/maziyarpanahi/openmed/blob/master/swift/OpenMedScanDemo/OpenMedScanDemo/ContentView.swift): app · Reference app showing model download, scan flow, and entity review. · `swift/OpenMedScanDemo/OpenMedScanDemo/ContentView.swift`

### Tooling and docs

Examples, documentation, tests, and release automation.

- [Examples](https://github.com/maziyarpanahi/openmed/blob/master/examples/obfuscation_demo.py): reference integrations · Python examples and notebooks demonstrating tokenization, PII, and zero-shot flows. · `examples/obfuscation_demo.py`
- [Docs site](https://github.com/maziyarpanahi/openmed/blob/master/docs/index.md): documentation · User guides, API docs, and published site content. · `docs/index.md`
- [Test suites](https://github.com/maziyarpanahi/openmed/blob/master/tests/unit/test_core.py): verification · Unit, integration, MLX, CoreML, service, and Swift tests covering the stack. · `tests/unit/test_core.py`

## Connections

- OpenMed API → Model registry: resolve model · Public calls look up model metadata and supported families.
- OpenMed API → Config and backends: select backend · API entry points route to the configured runtime and environment.
- OpenMed API → Text processing: preprocess · High-level helpers normalize text before inference.
- Text processing → Sentence split: segment · Text processing uses sentence boundaries for chunking and batching.
- Text processing → NER inference: feed text · Prepared text is passed into NER inference.
- Model registry → Model families: family map · Registry entries determine which model family adapter to load.
- Config and backends → MLX stack: route mlx · Configuration can select the MLX execution path.
- Config and backends → CoreML export: route coreml · Configuration can target exported CoreML artifacts.
- Config and backends → Privacy filter: route torch · Configuration can target the Torch privacy-filter backend.
- NER inference → Model families: load adapter · Inference delegates to family-specific loaders and adapters.
- NER inference → Span decoding: decode spans · Raw model outputs are transformed into entity spans.
- Span decoding → Output formats: normalize · Decoded entities are converted into stable output structures.
- OpenMed API → PII pipeline: PII flow · PII extraction and de-identification are exposed as top-level helpers.
- PII pipeline → Anonymizer: mask content · Extracted entities are passed to the anonymization engine.
- PII pipeline → PII rules: locale rules · PII behavior is adjusted through locale and language registries.
- PII pipeline → Quality gates: gate output · PII results are checked for malformed or low-quality outputs.
- Batch processor → Text processing: reuse pipeline · Batch orchestration reuses the same text preprocessing path.
- Batch processor → NER inference: multi-text infer · Batch processing fans out over the core inference pipeline.
- Profiling tools → Batch processor: measure batches · Profiling tracks batch throughput and bottlenecks.
- FastAPI app → Service runtime: serve requests · The FastAPI app delegates runtime and model lifecycle handling.
- FastAPI app → API schemas: validate payloads · HTTP requests and responses use explicit schemas.
- Service runtime → OpenMed API: call core API · The service layer wraps the same Python helpers used by local callers.
- MLX stack → Model families: mlx models · MLX inference uses specialized native model implementations and adapters.
- MLX stack → Model registry: artifact lookup · MLX artifacts are selected via model metadata and registry entries.
- CoreML export → Model registry: export models · CoreML export depends on the same model registry and family metadata.
- OpenMedKit → MLX stack: consume artifacts · Swift runtime consumes MLX-compatible model artifacts.
- OpenMedKit → CoreML export: load coreml · Swift package also supports bundled CoreML assets.
- OpenMedKit → Output formats: post-process · Swift mirrors Python post-processing and entity formatting.
- Swift demo → OpenMedKit: use runtime · Demo apps are built on top of the Swift package.
- Docs site → OpenMed API: document · Docs explain the public Python API and workflows.
- Docs site → FastAPI app: document · Docs cover REST deployment and service usage.
- Test suites → OpenMed API: verify · Tests cover public helpers, routing, and output behavior.
- Test suites → MLX stack: verify · Tests validate MLX conversion and inference.
- Test suites → CoreML export: verify · Tests validate CoreML export.
- Test suites → FastAPI app: verify · Tests validate the service API boundary.
- Test suites → OpenMedKit: verify · Swift tests keep the package aligned with Python behavior.
