Skip to main content

Maintained as part of the rettX program — the patient registry initiative of Rett Syndrome Europe. The library is general-purpose and can be used standalone. It is also the canonical HGVS mutation parsing & normalisation component used by rettxapi.

RettX Mutation Analysis Library

PyPI version Python 3.8+ License: MIT

A Python library for extracting and validating genetic mutations from clinical reports using an AI-powered agentic pipeline. Supports 6 Rett Syndrome-related genes across multiple languages, returning fully normalized HGVS nomenclature with genomic coordinates on both GRCh37 and GRCh38 assemblies.

🚀 Quick Start

Installation

pip install rettxmutation

Basic Usage

import asyncio
from rettxmutation import RettxServices, DefaultConfig

async def extract():
    config = DefaultConfig()  # loads from .env / environment variables

    with RettxServices(config) as services:
        result = await services.agent_extraction_service.extract_mutations(
            "The patient carries the mutation NM_004992.4:c.916C>T (p.Arg306Cys) in MECP2."
        )

        for key, mutation in result.mutations.items():
            pt = mutation.primary_transcript
            print(f"Gene:       {pt.gene_id}")
            print(f"Transcript: {pt.hgvs_transcript_variant}")
            print(f"Protein:    {pt.protein_consequence_tlr}")
            print(f"Type:       {mutation.variant_type}")
            for assembly, coord in mutation.genomic_coordinates.items():
                print(f"{assembly}:    {coord.hgvs}  (pos {coord.start:,}–{coord.end:,})")

asyncio.run(extract())

CLI Example

python examples/extract_from_file.py path/to/genetic_report.txt --verbose

✨ Key Features

  • 🧬 Multi-Gene Support: MECP2, FOXG1, SLC6A1, CDKL5, EIF2B2, MEF2C — with curated RefSeq transcripts
  • 🌍 Multilingual: Processes reports in English, Spanish, Greek, Turkish, and more
  • 🤖 Agentic Extraction: Azure OpenAI-powered agent with tool-calling (gene registry lookup, variant validation, complex variant handling)
  • ✅ HGVS Validation: Every mutation is validated via VariantValidator with automatic coordinate liftover (GRCh37 ↔ GRCh38)
  • 🔒 PHI Redaction: Automatic removal of personal health information before LLM processing
  • ⚡ Production Ready: Type-safe Pydantic v2 models, exponential backoff, connection pooling
  • 🔄 Dual Assembly Output: Every mutation includes genomic coordinates on both GRCh37 and GRCh38
  • 🏗️ Modular Architecture: Lazy-initialized services with dependency injection and context manager support

🧬 Supported Genes

Gene Chromosome Primary Transcript Condition
MECP2 Xq28 NM_004992.4 (+NM_001110792.2) Classic Rett Syndrome
FOXG1 14q12 NM_005249.5 Congenital variant Rett
SLC6A1 3p25.3 NM_003042.4 Myoclonic-atonic epilepsy
CDKL5 Xp22.13 NM_001323289.2 CDKL5 deficiency disorder
EIF2B2 14q24.3 NM_014239.4 Vanishing white matter disease
MEF2C 5q14.3 NM_002397.5 (+NM_001131005.2) MEF2C haploinsufficiency

📊 Output Structure

The ExtractionResult contains:

ExtractionResult
├── mutations: Dict[str, GeneMutation]    ← keyed by GRCh38 genomic HGVS
├── genes_detected: List[str]             ← e.g. ["MECP2"]
├── extraction_log: List[str]             ← agent reasoning trace
└── tool_calls_count: int                 ← total tool invocations

Each GeneMutation provides:

GeneMutation
├── genomic_coordinates:
│   ├── GRCh38: { assembly, hgvs, start, end, size }
│   └── GRCh37: { assembly, hgvs, start, end, size }
├── variant_type: "SNV" | "deletion" | "duplication" | "insertion" | "indel"
├── primary_transcript:
│   ├── gene_id, transcript_id
│   ├── hgvs_transcript_variant      ← e.g. NM_004992.4:c.916C>T
│   ├── protein_consequence_tlr      ← e.g. NP_004983.1:p.(Arg306Cys)
│   └── protein_consequence_slr      ← e.g. NP_004983.1:p.(R306C)
└── secondary_transcript (optional)

🛠️ Requirements

Python Version

  • Python 3.8 or higher

Azure Services

Service Required? Purpose
Azure OpenAI ✅ Required Agentic mutation extraction
Azure AI Search Optional Semantic search for keyword detection
Azure Cognitive Services Optional Text analytics enrichment

Environment Variables

# Required — Azure OpenAI
RETTX_OPENAI_ENDPOINT=https://your-openai.openai.azure.com/
RETTX_OPENAI_KEY=your-openai-key
RETTX_OPENAI_MODEL_NAME=gpt-4o           # deployment name

# Optional — Agent model (defaults to RETTX_OPENAI_MODEL_NAME if not set)
RETTX_OPENAI_AGENT_DEPLOYMENT=gpt-4o     # agent-specific deployment
RETTX_OPENAI_AGENT_MODEL_VERSION=2024-11-20

# Optional — Embeddings
RETTX_EMBEDDING_DEPLOYMENT=text-embedding-ada-002

# Optional — Azure AI Search
RETTX_AI_SEARCH_SERVICE=your-search-service
RETTX_AI_SEARCH_API_KEY=your-search-key
RETTX_AI_SEARCH_INDEX_NAME=your-index-name

# Optional — Azure Cognitive Services
RETTX_COGNITIVE_SERVICES_ENDPOINT=https://your-cognitive-services.cognitiveservices.azure.com/
RETTX_COGNITIVE_SERVICES_KEY=your-cognitive-services-key

📋 Processing Pipeline

The agentic extraction pipeline works as follows:

Input Text (any language)
    │
    ▼
┌──────────────────────┐
│  PHI Redaction        │  Remove patient names, DOBs, IDs
└──────────┬───────────┘
           ▼
┌──────────────────────┐
│  AI Agent (OpenAI)    │  Reads text, identifies mutations
│                      │
│  Tools available:    │
│  • lookup_gene_registry  → gene info + RefSeq transcripts
│  • validate_variant      → HGVS validation + coordinates
│  • validate_complex      → CNV / genomic coordinate validation
└──────────┬───────────┘
           ▼
┌──────────────────────┐
│  Structured Output    │  ExtractionResult with validated
│                      │  GeneMutation objects
└──────────────────────┘

Key capabilities:

  • Ensembl → RefSeq remapping: Handles reports using Ensembl transcripts (ENST*) by using genomic coordinates
  • Minus-strand awareness: Correctly complements alleles for genes on the reverse strand
  • Old nomenclature: Normalizes legacy formats (e.g., 502C->T, R168X) to current HGVS

💻 Available Services

All services are lazily initialized via RettxServices:

with RettxServices(config) as services:
    # Core extraction
    services.agent_extraction_service    # AI-powered mutation extraction
    
    # Validation & analysis
    services.variant_validator_service   # HGVS validation + coordinate liftover
    services.mutation_tokenizator        # Mutation string tokenization
    
    # Search & embeddings
    services.embedding_service           # Azure OpenAI embeddings
    services.ai_search_service           # Azure AI Search integration
    services.keyword_detector_service    # Multi-layer keyword detection

Direct Variant Validation

Use this to validate a single manually entered variant (for example an admin-entered variant, or a variant proposed by an expert reviewer). It applies the same rules as the extraction pipeline: the variant is normalized by the external VariantValidator, lifted over to GRCh38 and GRCh37, and annotated on the gene's registry transcripts. It only returns a GeneMutation; it never stores or changes anything, so the caller decides whether and when to apply the result.

from rettxmutation.models.gene_assembly import GenomeAssembly
from rettxmutation.repositories.variant_validator_repository import (
    VariantValidatorNormalizationError,
)

with RettxServices(config) as services:
    vvs = services.variant_validator_service

    # Transcript-level variant (c. HGVS on a transcript, gene from the registry)
    result = vvs.create_gene_mutation_from_transcript_variant(
        hgvs_string="NM_004992.4:c.916C>T",
        gene_symbol="MECP2",
    )
    print(result.genomic_coordinate)
    # → NC_000023.11:g.154030912G>A
    print(result.primary_transcript.protein_consequence_tlr)
    # → NP_004983.1:p.(Arg306Cys)

    # Complex / genomic variant (g. HGVS); gene_symbol adds transcript annotations
    result = vvs.create_gene_mutation_from_complex_variant(
        gene_assembly=GenomeAssembly(build="GRCh38", chromosome="chrX", refseq="NC_000023.11"),
        variant_description="NC_000023.11:g.154030912G>A",
        gene_symbol="MECP2",
    )

An invalid variant is never returned as a result. Both methods raise:

  • ValueError — malformed input (e.g. not TRANSCRIPT:detail), unknown gene symbol, or unknown/unavailable transcript.
  • VariantValidatorNormalizationError — VariantValidator rejected the variant (warnings, errors, empty data). When it wraps a transport failure, the original requests exception is chained as its __cause__.
  • requests.exceptions.HTTPError — rate limiting (HTTP 429) still failing after retries.

The client is synchronous; async callers should run it in a worker thread (e.g. asyncio.to_thread).

Custom Configuration

class MyConfig:
    """Custom configuration for production (e.g., from Key Vault)."""
    RETTX_OPENAI_ENDPOINT = "https://my-openai.openai.azure.com/"
    RETTX_OPENAI_KEY = get_secret("openai-key")
    RETTX_OPENAI_MODEL_NAME = "gpt-4o"
    # Only set fields needed for the services you use

with RettxServices(MyConfig()) as services:
    result = await services.agent_extraction_service.extract_mutations(text)

🧪 Golden Test Suite

The library includes a comprehensive golden test suite with 11 real-world genetic reports:

Gene Variant Type Language Key Feature
MECP2 SNV, splicing, deletion, duplication EN, ES, EL, TR Multiple transcripts
FOXG1 Frameshift deletion TR Non-MECP2 gene
SLC6A1 Whole-gene CNV (~20kb) ES Copy number variant

Run golden tests:

# Mock mode (no API calls, uses recorded responses)
python -m pytest tests/golden/ --golden-mode=mock -v

# Live mode (calls real APIs)
python -m pytest tests/golden/ --golden-mode=live -v

🎯 Use Cases

  • 🏥 Clinical Genetics: Extract mutations from diagnostic reports in any language
  • 🔬 Research: Analyze genetic data across Rett Syndrome and related conditions
  • 📊 Patient Registries: Populate genetic databases with normalized HGVS nomenclature
  • 🤖 Bioinformatics Pipelines: Integrate as a library or via the CLI example
  • 📱 Clinical Applications: Build tools with structured mutation data (dual-assembly coordinates)

🔧 Reliability

  • Exponential Backoff: Automatic retry for VariantValidator and OpenAI API calls
  • Graceful Degradation: Optional services (AI Search, Cognitive Services) degrade gracefully
  • PHI Redaction: Patient data is stripped before any LLM processing
  • Type Safety: Pydantic v2 models with runtime validation
  • Context Manager: Automatic resource cleanup via with statement
  • Comprehensive Logging: Structured extraction logs with tool call traces

🤝 Contributing

We welcome contributions! Please see our GitHub repository for:

  • Issue reporting
  • Feature requests
  • Pull request guidelines
  • Development setup instructions

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

🔮 Roadmap

  • Additional Genes: Expand the gene registry beyond the current 6 genes
  • Batch Processing: Process multiple reports in parallel with rate limiting
  • Confidence Scoring: Per-mutation confidence metrics based on report quality
  • Structured Report Parsing: Native support for VCF, JSON, and HL7 FHIR formats
  • Cloud Deployment: Docker containers and Azure deployment templates

Metadata

Release files for rettxmutation 0.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rettxmutation 0.4.1
File Size Uploaded Provenance Actions
rettxmutation-0.4.1.tar.gz 81.5 kB With provenance Details for rettxmutation-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rettxmutation 0.4.1
File Interpreter ABI Platform Actions
rettxmutation-0.4.1-py3-none-any.whl Python 3 none any Details for rettxmutation-0.4.1-py3-none-any.whl

Total release size: 155.2 kB

Release files / rettxmutation-0.4.1.tar.gz

Download URL rettxmutation-0.4.1.tar.gz
Size 81.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1c4eb50706e90b6336bee8b55e344583a35b4316e6450bd37df5a62b8aba33d6
BLAKE2b-256 checksum
How to use checksums
bb60c5c9d4565751cca7c143ffb830e827914ab04e2fd38ae0f939819a56be1e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / rettxmutation-0.4.1-py3-none-any.whl

Download URL rettxmutation-0.4.1-py3-none-any.whl
Size 73.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
da3d0749f59900b96de0542aa5fad17fe59da43e0f4991572eac79fa2d8f253e
BLAKE2b-256 checksum
How to use checksums
bcf9dc32cf47785eb9b45e1aa25f76b8e8985312d4ee64c3ceba0aaf7b7032a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for rettxmutation 0.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for rettxmutation-0.4.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.4.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page