How maziyarpanahi/openmed works
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: __init__.py OpenMed API · test_core.py Test suites · OpenMedKit.swift OpenMedKit · inference.py MLX stack
Components 26
Python library
Primary medical NLP and de-identification stack.
- OpenMed API · High-level entry points such as analyze_text, extract_pii, deidentify, and batch processing.
openmed/__init__.py - Model registry · Maps model names and families to metadata and supported runtimes.
openmed/core/model_registry.py - Config and backends · Resolves environment, backend selection, and runtime configuration.
openmed/core/config.py - Text processing · Tokenization, sentence splitting, and text normalization before inference.
openmed/processing/text.py - Sentence split · Sentence and document segmentation used by batch and NER pipelines.
openmed/processing/sentences.py - NER inference · Adapter and inference layer for family-specific model execution.
openmed/ner/infer.py - Model families · Family-specific loaders and adapters for GLiNER-style and related NER models.
openmed/ner/families/base.py - Span decoding · Converts token-level outputs into entity spans and labels.
openmed/core/decoding/spans.py - Output formats · Normalizes results into dict, JSON, HTML, and CSV-like representations.
openmed/processing/outputs.py - PII pipeline · PII extraction and masking flow built on top of NER spans.
openmed/core/pii.py - Anonymizer · Performs redact, replace, hash, date-shift, and locale-aware substitutions.
openmed/core/anonymizer/engine.py - PII rules · Language and locale registries for multilingual PII handling.
openmed/core/pii_i18n.py - Quality gates · Checks malformed inputs, unsupported configurations, and output quality.
openmed/core/quality_gates.py - Batch processor · Coordinates multi-text workflows with aggregation and thresholds.
openmed/processing/batch.py - Profiling tools · Timing and bottleneck visibility without changing model logic.
openmed/utils/profiling.py
Runtime backends
Alternative execution paths for model inference and export.
- MLX stack · MLX artifact, conversion, inference, and native model implementations.
openmed/mlx/inference.py - CoreML export · Exports supported models into CoreML artifacts for Apple platforms.
openmed/coreml/convert.py - Privacy filter · 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 · REST service entry point with health and analysis endpoints.
openmed/service/app.py - Service runtime · Shared model preload, request lifecycle, and error envelopes.
openmed/service/runtime.py - API schemas · Request and response schemas for the service boundary.
openmed/service/schemas.py
Swift package
Apple-platform runtime and demos.
- OpenMedKit · Swift-side model store, pipelines, and post-processing for Apple apps.
swift/OpenMedKit/Sources/OpenMedKit/OpenMedKit.swift - Swift demo · 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 · Python examples and notebooks demonstrating tokenization, PII, and zero-shot flows.
examples/obfuscation_demo.py - Docs site · User guides, API docs, and published site content.
docs/index.md - Test suites · Unit, integration, MLX, CoreML, service, and Swift tests covering the stack.
tests/unit/test_core.py
Connections 36
- 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.