Metadata-Version: 2.4
Name: opensafety
Version: 0.3.3
Summary: Open-source Pharmacovigilance AI for ADR extraction, MedDRA coding, and listedness assessment
Author: OpenSafety Team
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/opensafety/opensafety
Project-URL: Bug Tracker, https://github.com/opensafety/opensafety/issues
Keywords: pharmacovigilance,meddra,adr,safety,clinical-nlp,drug-safety
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Healthcare Industry
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.1
Requires-Dist: transformers>=4.45
Requires-Dist: huggingface-hub>=0.24
Requires-Dist: numpy>=1.24
Provides-Extra: pdf
Requires-Dist: pymupdf; extra == "pdf"
Provides-Extra: docx
Requires-Dist: python-docx; extra == "docx"
Provides-Extra: full
Requires-Dist: pymupdf; extra == "full"
Requires-Dist: python-docx; extra == "full"
Requires-Dist: pypdf; extra == "full"
Requires-Dist: pdfplumber; extra == "full"
Dynamic: license-file

# OpenSafety 🩺

[![PyPI version](https://img.shields.io/pypi/v/opensafety.svg)](https://pypi.org/project/opensafety/)
[![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97%20Model-OpenSafety--1.5B-yellow)](https://huggingface.co/thesumith/opensafety-1.5b)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

**OpenSafety** is an open-source Pharmacovigilance (PV) AI toolkit powered by the **OpenSafety-1.5B** foundation model and deterministic **MedDRA v28.0** ontology verification for:
1. **Adverse Drug Reaction (ADR) Extraction** from raw clinical text.
2. **MedDRA Coding** (LLT, Preferred Term, and Primary System Organ Class).
3. **Regulatory Listedness Assessment** against Reference Safety Information (RSI / Product Labels).

---

## Installation

```bash
pip install opensafety
```

---

## 💻 Effortless Terminal CLI Usage

OpenSafety provides an interactive, terminal-first interface designed for effortless case reviews:

### 1. Interactive Guided Wizard (Paste Narrative & Attach RSI):
Simply run `opensafety` in your terminal:
```bash
opensafety
```
- **Step 1: Paste Narrative or Drag-and-Drop File**:
  - Paste your multi-line clinical narrative (press Enter twice or type `DONE` to finish).
  - Or simply **drag & drop** a case file (`.pdf`, `.docx`, `.txt`, `.md`) directly into the terminal window!
  - Or press `D` to immediately run the built-in clinical demo case.
- **Step 2: Attach Reference Safety Information (RSI)**:
  - Drag & drop an SmPC / USPI / IB document (`.pdf`, `.docx`, `.txt`), OR
  - Paste Section 4.8 / Undesirable Effects text directly, OR
  - Press Enter to skip (performs ADR coding without listedness).
- **Step 3: Suspect Drug Name (Optional)**:
  - Type the drug name, or press Enter to auto-extract suspect drugs directly from the narrative!
- **Step 4: Real-time Analysis & Validation**:
  - Outputs color-coded cards (`🟢 LISTED` vs `🔴 UNLISTED`, `✅ VERIFIED MedDRA v28.0`).
  - Option to save as JSON or an ICH E2B(R3) ICSR (`.xml`).

### 2. Instant Built-in Demo Case:
```bash
opensafety demo
```
Runs an end-to-end clinical case (Atorvastatin with Rhabdomyolysis and Acute Renal Failure against SmPC Section 4.8) in seconds.

### 3. Command-Line File / Pipe Mode:
```bash
# Attach PDF / Word documents directly:
opensafety analyze --narrative case.pdf --rsi smpc_section_4_8.docx -o report.json

# Or pipe text from another command or file:
cat case_narrative.txt | opensafety analyze --rsi label.pdf
```

### 4. Fast MedDRA v28.0 Ontology Lookup:
```bash
opensafety lookup "muscle pain"
opensafety lookup "rhabdomyolysis"
```

---

## Quick Start: End-to-End AI Pharmacovigilance

```python
from opensafety import OpenSafetyEngine

# 1. Initialize the engine (automatically loads the OpenSafety-1.5B model)
engine = OpenSafetyEngine()

# 2. Analyze a raw patient narrative
report = engine.analyze(
    drug="Atorvastatin",
    narrative="A 62-year-old female taking Atorvastatin 40mg daily developed acute muscle weakness and soreness in her calves.",
    rsi="Section 4.8 Undesirable Effects: Common: myalgia, arthralgia, pain in extremity, muscle spasms."
)

# 3. Inspect verified regulatory output
for event in report.adverse_events:
    print(f"Verbatim: {event.verbatim}")
    print(f"MedDRA PT: {event.meddra_pt} (Code: {event.meddra_pt_code})")
    print(f"Primary SOC: {event.meddra_soc}")
    print(f"Listedness: {event.listedness.status}")
    print(f"Rationale: {event.listedness.rationale}")
    print(f"Validation: {event.validation_status}")
```

---

### Instant MedDRA v28.0 Dictionary & Fuzzy Search

```python
from opensafety import MedDRADatabase, HybridMedDRAMatcher

# Exact dictionary lookup (89,774 LLTs & 26,920 PTs)
db = MedDRADatabase("meddra.db")
res = db.search_term("Dry cough")
print(res[0]["pt_name"])  # "Cough"
print(res[0]["soc_name"]) # "Respiratory, thoracic and mediastinal disorders"

# Colloquial fuzzy matching for patient expressions
matcher = HybridMedDRAMatcher("meddra.db")
matches = matcher.search("stomach ache", top_k=1)
print(matches[0]["pt_name"])  # "Abdominal pain upper"
```

---

## Architecture: Hybrid Safety Engine

```
[ Clinical Narrative / Case Report ] + [ Reference Safety Info (RSI) ]
                                  │
                                  ▼
               OpenSafety-1.5B Clinical Foundation Model
                                  │
                                  ▼
                     Extracted Structured JSON
                                  │
                                  ▼
         Deterministic MedDRA v28.0 SQLite Verification
            (Zero hallucination, verified 8-digit codes)
                                  │
                                  ▼
              Validated ICH E2B(R3) Structured Report
```

---

## License

Apache License 2.0. MedDRA is copyrighted by the International Council for Harmonisation (ICH) and maintained by MSSO.
