Guide me about respiratory failure

Reading File
Finding Sources
Finding Sources
Searching PubMed

"respiratory failure" management

Reading File
Reading File
Reading File
Reading File
Reading File
Loading Image
Reading File
Reading File
I now have comprehensive content from multiple authoritative textbooks. Let me compile the full guide.

Respiratory Failure: A Comprehensive Guide

Classification of Respiratory Failure
Classification of respiratory failure - Fishman's Pulmonary Diseases and Disorders

Definition

Respiratory failure is a condition in which the respiratory system fails in one or both of its gas-exchanging functions: oxygenation of mixed venous blood and CO2 elimination from it. It is a syndrome, not a disease - many underlying conditions can cause it.
  • Fishman's Pulmonary Diseases and Disorders, Ch. 139

Classification

By Gas Exchange Abnormality

TypeDefinitionKey Feature
Hypoxemic (Type 1)PaO2 < 60 mmHgFailure of oxygenation
Hypercapnic (Type 2)PaCO2 > 45 mmHgFailure of ventilation / CO2 removal; respiratory acidosis (pH < 7.35)
Postoperative (Type 3)Atelectasis post-surgery due to pain or sedativesSubset of Type 1 or 2; very common
Shock-related (Type 4)Metabolic demands exceed respiratory capacity (e.g., sepsis, fever)Intubation to off-load respiratory work
MixedCoexistent hypoxemia and hypercapniaMost common in clinical practice

By Time Course

CategoryOnsetKey Feature
AcuteMinutes to hoursLife-threatening ABG/acid-base derangements
ChronicDays or longerIndolent; renal bicarbonate compensation may mask severity
Chronic hypercapnic failure (e.g., COPD): kidneys retain HCO3- over time. A superimposed acute rise in PaCO2 has a less dramatic pH drop than in patients with normal baseline bicarbonate.
  • Washington Manual of Medical Therapeutics, p. 276

Pathophysiology

Respiratory failure arises from failure at any component of the respiratory system:
CNS → Peripheral Nerves → Respiratory Muscles/Chest Wall → Airways → Alveoli
        [These 4 = "Respiratory Pump"]              [Alveolar disease → hypoxemia]
Pump failure (first 4 components) typically causes both hypercapnia and hypoxemia. Alveolar disorders initially cause hypoxemia alone.
  • Fishman's Pulmonary Diseases and Disorders, Ch. 139

5 Mechanisms of Hypoxemia (Type 1)

MechanismExampleA-a GradientO2 Response
V/Q mismatchPneumonia, COPD, PE, pulmonary edemaElevatedImproves with O2
ShuntARDS, atelectasis, intracardiac shuntElevatedDoes NOT improve with O2
Diffusion impairmentInterstitial lung diseaseElevatedImproves with O2
HypoventilationCNS/NMJ depressionNormalImproves with O2
Low inspired FiO2High altitudeNormalImproves with O2
Note: In emphysema, supplemental O2 can paradoxically worsen V/Q mismatch by reversing hypoxic vasoconstriction of poorly ventilated capillaries.
  • Washington Manual, p. 277

Ventilatory Supply vs. Demand (Hypercapnic Failure)

Hypercapnic failure occurs when ventilatory demand exceeds supply:
Factors reducing supply (ventilatory pump failure):
  • Muscle fatigue, disuse atrophy, malnutrition
  • Low phosphate/potassium (electrolyte disturbances)
  • Neuropathy (Guillain-Barre, phrenic nerve injury)
  • Neuromuscular junction disease (myasthenia gravis)
  • Airway obstruction (bronchospasm, excessive secretions)
  • Restricted chest wall movement (pain, obesity, ascites)
Factors increasing demand:
  • Increased dead space (V_D/V_T): asthma, emphysema, ARDS, PE
  • Increased metabolic rate: fever, sepsis, trauma, shivering
  • Excessive carbohydrate feeding (raises RQ, more CO2 produced)
  • Fishman's Pulmonary Diseases and Disorders, Tables 139-2 and 139-3

Causes by System

SystemExamples
CNSNarcotic/sedative overdose, stroke, head trauma, metabolic encephalopathy
Peripheral NSGuillain-Barre, poliomyelitis, phrenic nerve injury
Neuromuscular junctionMyasthenia gravis, botulism, organophosphate poisoning
Respiratory musclesFatigue, myopathy, malnutrition
Airways (upper)Angioedema, foreign body, epiglottitis
Airways (lower)Acute asthma, COPD exacerbation
Lung parenchymaPneumonia, ARDS, pulmonary edema
Pleura/chest wallPneumothorax, massive effusion, flail chest
Pulmonary vasculatureMassive PE

Clinical Assessment

Symptoms

  • Dyspnea, tachypnea, use of accessory muscles
  • Cyanosis (late, unreliable sign)
  • Altered mental status (confusion, agitation, somnolence) - especially in hypercapnia
  • In COPD exacerbation: increasing dyspnea + sputum production preceding acute-on-chronic failure

Key Investigations

  • Arterial blood gas (ABG): confirms diagnosis; identifies type and severity
  • A-a gradient: helps determine mechanism of hypoxemia
    • Formula: PAO2 = FiO2 x (PATM - PH2O) - PaCO2/R
  • CXR/CT chest: identifies underlying cause
  • ECG: rule out cardiac cause
  • Markers of chronicity: polycythemia (chronic hypoxemia), cor pulmonale

Management

Step 1: Oxygen Supplementation (first-line for hypoxemia)

DeviceFiO2 DeliveredNotes
Nasal cannula~24-44% (4% per L/min)Max 6 L/min; FiO2 imprecise
Simple face mask35-55% at 5-12 L/minAvoid < 5 L/min (CO2 rebreathing)
Venturi mask24, 28, 31, 35, 40, 50%Most precise FiO2 delivery
Non-rebreathing maskUp to 80%8-15 L/min; one-way valve
HFNCUp to 100% at 60 L/minFlushes dead space; provides small PEEP benefit
HFNC vs standard O2/NPPV: One open-label trial showed no difference in intubation rate, but significant improvement in 90-day mortality with HFNC. A meta-analysis of 9 trials showed HFNC decreased need for intubation and escalation of therapy.
  • Washington Manual, p. 279
Caution with hypercapnic (COPD) patients: titrate O2 carefully to SpO2 88-92% to avoid suppressing hypoxic drive and worsening hypercapnia.

Step 2: Non-Invasive Positive Pressure Ventilation (NPPV)

CPAP:
  • Delivers constant pressure throughout respiratory cycle
  • Prevents alveolar collapse
  • Used in: pulmonary edema, OSA, hypoxemic failure
  • Start: 5 cm H2O, increase by 3-5 cm H2O to max 10-15 cm H2O
BiPAP:
  • Provides higher pressure during inspiration, lower during expiration
  • Reduces work of breathing; assists ventilation
  • Used in: COPD exacerbations, neuromuscular weakness, weaning
  • Start: IPAP 10-15 cm H2O, EPAP 5 cm H2O
Benefits of NPPV:
  • Decreases need for intubation
  • Preserves upper airway reflexes
  • Avoids ventilator-associated complications
Contraindications to NPPV (intubate instead):
  • Inability to protect airway / altered consciousness
  • Hemodynamic instability
  • Uncooperative patient
  • Facial trauma

Step 3: Invasive Mechanical Ventilation

Indicated when NPPV fails or is contraindicated.
Key principles:
  • Modern PPV is the standard (negative pressure "iron lung" is historical)
  • Modes: volume control, pressure control, AC, SIMV, PSV, PRVC, APRV, HFOV
    • No strong evidence that mode choice affects major outcomes - clinician preference drives selection
  • Tidal volumes: Use lung-protective 6 mL/kg IBW (not 10-15 mL/kg) to prevent ventilator-induced lung injury (VILI)
  • PEEP: maintains alveolar recruitment; reduces shunt fraction
Complications of mechanical ventilation:
  • Auto-PEEP / air trapping (especially in obstructive disease)
  • Barotrauma: pneumothorax, pneumomediastinum, subcutaneous emphysema
  • Reduced cardiac output (PPV increases intrathoracic pressure, reduces venous return)
  • Ventilator-associated lung injury (VALI/VILI)
  • Barash's Clinical Anesthesia, Ch. 57

Treating the Underlying Cause

This is always the definitive treatment:
  • Sepsis → antibiotics, source control
  • Pulmonary edema → diuresis, vasodilators
  • COPD exacerbation → bronchodilators, steroids
  • Narcotic overdose → naloxone
  • Pneumothorax → chest tube
  • Myasthenia crisis → IVIG/plasmapheresis

ARDS (Most Severe Form of Type 1 Failure)

Berlin Definition Criteria:
  1. Onset within 1 week of clinical insult
  2. Bilateral opacities on CXR (not explained by effusion/collapse/nodules)
  3. Respiratory failure not fully explained by cardiac failure/volume overload
  4. PaO2/FiO2 ratio ≤ 300 mmHg
Severity Stratification:
SeverityPaO2/FiO2PEEP
Mild200-300 mmHg≥ 5 cm H2O
Moderate100-200 mmHg≥ 5 cm H2O
Severe≤ 100 mmHg≥ 5 cm H2O
  • Washington Manual, p. 276

Weaning from Mechanical Ventilation

Readiness criteria (general):
  • Underlying cause improving
  • Adequate oxygenation (PaO2/FiO2 > 150-200, PEEP ≤ 5-8, FiO2 ≤ 0.4-0.5)
  • Hemodynamically stable
  • Adequate respiratory effort
  • Able to follow commands / protect airway
Standard approach: Spontaneous Breathing Trial (SBT) - a 30-120 min trial on low support (PSV 5/CPAP 5 or T-piece). Pass → extubate. Fail → investigate why and address.

Summary Table: Type 1 vs Type 2 Failure

FeatureType 1 (Hypoxemic)Type 2 (Hypercapnic)
Primary defectOxygenationVentilation
ABGPaO2 < 60PaCO2 > 45, pH < 7.35
A-a gradientUsually elevatedNormal (unless concurrent lung disease)
Typical causesARDS, pneumonia, PE, pulmonary edemaCOPD, asthma, NMJ disease, CNS depression
O2 therapyEffective (except shunt)Use cautiously; target SpO2 88-92% in COPD
Preferred NIVCPAP or HFNCBiPAP

Sources:
  • Fishman's Pulmonary Diseases and Disorders, Ch. 139 (Respiratory Failure: An Overview)
  • The Washington Manual of Medical Therapeutics (Respiratory Failure, pp. 276-284)
  • Barash's Clinical Anesthesia, 9e, Ch. 57 (Acute Respiratory Failure)
  • Barash's Clinical Anesthesia, 9e (Mechanical Ventilation)

Make a quick reference PDF for respiratory failure types & management

Reading File
Running Command

ls -la /home/daytona/workspace/ 2>/dev/null || echo "workspace not found"

Running Command

mkdir -p /home/daytona/workspace/respiratory-failure-pdf && echo "created"

Writing File

~/respiratory-failure-pdf/generate_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm, mm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, KeepTogether
)
from reportlab.platypus import PageBreak
from reportlab.lib.colors import HexColor
import os

OUTPUT_PATH = "/home/daytona/workspace/respiratory-failure-pdf/Respiratory_Failure_Quick_Reference.pdf"

# ── Colour palette ──────────────────────────────────────────────────────────
C_HEADER_BG   = HexColor("#1B3A6B")   # deep navy
C_HEADER_TEXT = colors.white
C_SECTION_BG  = HexColor("#2B6CB0")   # medium blue
C_SECTION_TEXT= colors.white
C_TYPE1       = HexColor("#2D6A4F")   # teal-green (hypoxemic)
C_TYPE2       = HexColor("#7B341E")   # rust-brown (hypercapnic)
C_TYPE3       = HexColor("#553C9A")   # purple (post-op)
C_TYPE4       = HexColor("#C05621")   # amber (shock)
C_ROW_ALT     = HexColor("#EBF4FF")   # light blue alt row
C_ROW_NORM    = colors.white
C_BORDER      = HexColor("#BEE3F8")
C_SUBHEAD_BG  = HexColor("#EBF8FF")
C_SUBHEAD_TEXT= HexColor("#1A365D")
C_MECH_BG     = HexColor("#F0FFF4")
C_WARN_BG     = HexColor("#FFFBEB")
C_WARN_BORDER = HexColor("#F6AD55")
C_MGMT_BG     = HexColor("#EBF4FF")
C_FOOTER      = HexColor("#718096")

W, H = A4

def build_styles():
    base = getSampleStyleSheet()
    styles = {}

    styles["title"] = ParagraphStyle(
        "title", fontSize=22, textColor=C_HEADER_TEXT,
        fontName="Helvetica-Bold", alignment=TA_CENTER, leading=26
    )
    styles["subtitle"] = ParagraphStyle(
        "subtitle", fontSize=10, textColor=HexColor("#BEE3F8"),
        fontName="Helvetica", alignment=TA_CENTER, leading=14
    )
    styles["section"] = ParagraphStyle(
        "section", fontSize=12, textColor=C_SECTION_TEXT,
        fontName="Helvetica-Bold", alignment=TA_LEFT, leading=16,
        leftIndent=6
    )
    styles["body"] = ParagraphStyle(
        "body", fontSize=8.5, textColor=HexColor("#1A202C"),
        fontName="Helvetica", leading=12, spaceAfter=2
    )
    styles["bold"] = ParagraphStyle(
        "bold", fontSize=8.5, textColor=HexColor("#1A202C"),
        fontName="Helvetica-Bold", leading=12
    )
    styles["small"] = ParagraphStyle(
        "small", fontSize=7.5, textColor=HexColor("#4A5568"),
        fontName="Helvetica", leading=10
    )
    styles["warning"] = ParagraphStyle(
        "warning", fontSize=8, textColor=HexColor("#744210"),
        fontName="Helvetica-BoldOblique", leading=11
    )
    styles["cell"] = ParagraphStyle(
        "cell", fontSize=8, textColor=HexColor("#1A202C"),
        fontName="Helvetica", leading=11
    )
    styles["cell_bold"] = ParagraphStyle(
        "cell_bold", fontSize=8, textColor=HexColor("#1A202C"),
        fontName="Helvetica-Bold", leading=11
    )
    styles["cell_hdr"] = ParagraphStyle(
        "cell_hdr", fontSize=8.5, textColor=colors.white,
        fontName="Helvetica-Bold", leading=11, alignment=TA_CENTER
    )
    return styles

S = build_styles()

def section_header(title):
    tbl = Table([[Paragraph(title, S["section"])]], colWidths=[W - 3*cm])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), C_SECTION_BG),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    return tbl

def p(text, style="body"): return Paragraph(text, S[style])
def sp(h=4): return Spacer(1, h)

# ── Content builders ─────────────────────────────────────────────────────────

def build_header_block():
    header_data = [[
        Paragraph("RESPIRATORY FAILURE", S["title"]),
    ],[
        Paragraph("Quick Reference Card  •  ICU / Emergency Medicine  •  Based on Fishman's Pulmonary Diseases, Washington Manual & Barash's Clinical Anesthesia", S["subtitle"]),
    ]]
    tbl = Table(header_data, colWidths=[W - 3*cm])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), C_HEADER_BG),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("ALIGN", (0,0), (-1,-1), "CENTER"),
    ]))
    return tbl


def build_definition():
    items = [
        section_header("▸  DEFINITION"),
        sp(4),
        p("Respiratory failure is a <b>syndrome</b> in which the respiratory system fails in one or both gas-exchange functions: <b>oxygenation</b> of mixed venous blood and/or <b>CO₂ elimination</b>. It is not a disease but the final common pathway of many disorders."),
        sp(3),
        p("• Diagnosed by <b>arterial blood gas (ABG)</b> — the gold standard."),
        p("• Tissue O₂ delivery also depends on cardiac output and hemoglobin concentration; these can cause tissue hypoxia without technically fulfilling ABG criteria."),
        sp(6),
    ]
    return items


def build_types_table():
    col_w = (W - 3*cm) / 5
    hdr = [
        p("Type", "cell_hdr"),
        p("Definition / Criterion", "cell_hdr"),
        p("Primary Defect", "cell_hdr"),
        p("Common Causes", "cell_hdr"),
        p("First-line Rx", "cell_hdr"),
    ]

    rows = [
        [
            p("<b>Type 1\nHypoxemic</b>", "cell_bold"),
            p("PaO₂ < 60 mmHg\n(Room air)", "cell"),
            p("Oxygenation failure;\nA-a gradient ↑", "cell"),
            p("Pneumonia, ARDS, PE, pulmonary oedema, atelectasis", "cell"),
            p("O₂ therapy, HFNC, CPAP", "cell"),
        ],
        [
            p("<b>Type 2\nHypercapnic</b>", "cell_bold"),
            p("PaCO₂ > 45 mmHg\npH < 7.35", "cell"),
            p("Ventilatory pump\nfailure; A-a normal", "cell"),
            p("COPD exacerbation, asthma, NMJ disease, CNS depression, obesity hypoventilation", "cell"),
            p("BiPAP, treat cause;\ncautious O₂ (SpO₂ 88–92%)", "cell"),
        ],
        [
            p("<b>Type 3\nPost-op</b>", "cell_bold"),
            p("Atelectasis after\nsurgery", "cell"),
            p("Pain / sedation →\nalveolar collapse", "cell"),
            p("Post-abdominal/thoracic surgery, inadequate analgesia", "cell"),
            p("Incentive spirometry,\nNPPV, pain control", "cell"),
        ],
        [
            p("<b>Type 4\nShock-related</b>", "cell_bold"),
            p("Metabolic demand\nexceeds supply", "cell"),
            p("Respiratory muscles\nconsuming excess O₂", "cell"),
            p("Sepsis, haemorrhagic shock, high fever, severe metabolic acidosis", "cell"),
            p("Intubate to off-load\nrespiratory work;\ntreat shock", "cell"),
        ],
        [
            p("<b>Mixed</b>", "cell_bold"),
            p("Both hypoxaemia\n& hypercapnia", "cell"),
            p("Multiple simultaneous\npathophysiologies", "cell"),
            p("Most common in ICU patients", "cell"),
            p("Address each component\nindependently", "cell"),
        ],
    ]

    data = [hdr] + rows
    tbl = Table(data, colWidths=[col_w]*5, repeatRows=1)
    row_colors = [C_ROW_ALT, C_ROW_NORM, C_ROW_ALT, C_ROW_NORM, C_ROW_ALT]
    style = [
        ("BACKGROUND", (0,0), (-1,0), C_HEADER_BG),
        ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("TOPPADDING", (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]
    for i, c in enumerate(row_colors):
        style.append(("BACKGROUND", (0, i+1), (-1, i+1), c))
    # Colour-code type column
    type_colors = [C_TYPE1, C_TYPE2, C_TYPE3, C_TYPE4, HexColor("#4A5568")]
    for i, c in enumerate(type_colors):
        style.append(("TEXTCOLOR", (0, i+1), (0, i+1), c))

    tbl.setStyle(TableStyle(style))
    return tbl


def build_acute_vs_chronic():
    col_w = (W - 3*cm) / 3
    hdr = [p("Feature", "cell_hdr"), p("Acute", "cell_hdr"), p("Chronic", "cell_hdr")]
    rows = [
        [p("Onset", "cell"), p("Minutes – hours", "cell"), p("Days – weeks or longer", "cell")],
        [p("Compensation", "cell"), p("None (acute pH drop)", "cell"), p("Renal HCO₃⁻ retention (buffers pH)", "cell")],
        [p("Clinical clues", "cell"), p("Acute distress, altered mental status, haemodynamic instability", "cell"), p("Polycythaemia, cor pulmonale, barrel chest", "cell")],
        [p("ABG pH (hypercapnia)", "cell"), p("< 7.30 (acidosis)", "cell"), p("Near normal (compensated)", "cell")],
    ]
    data = [hdr] + rows
    tbl = Table(data, colWidths=[col_w*0.8, col_w*1.1, col_w*1.1], repeatRows=1)
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), C_HEADER_BG),
        ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [C_ROW_NORM, C_ROW_ALT]),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]))
    return tbl


def build_hypoxemia_mechanisms():
    col_w = (W - 3*cm) / 5
    hdr = [p("Mechanism", "cell_hdr"), p("Example", "cell_hdr"), p("A-a Gradient", "cell_hdr"), p("O₂ Response", "cell_hdr"), p("Key Clue", "cell_hdr")]
    rows = [
        [p("V/Q Mismatch", "cell_bold"), p("Pneumonia, COPD, PE, pulmonary oedema", "cell"), p("↑ Elevated", "cell"), p("Improves", "cell"), p("Most common cause", "cell")],
        [p("Shunt", "cell_bold"), p("ARDS, atelectasis, intracardiac shunt", "cell"), p("↑ Elevated", "cell"), p("Does NOT improve", "cell"), p("Refractory hypoxaemia", "cell")],
        [p("Diffusion Impairment", "cell_bold"), p("ILD, emphysema", "cell"), p("↑ Elevated", "cell"), p("Improves", "cell"), p("Worse with exercise", "cell")],
        [p("Hypoventilation", "cell_bold"), p("CNS depression, NMJ disease", "cell"), p("Normal", "cell"), p("Improves", "cell"), p("CO₂ also elevated", "cell")],
        [p("Low FiO₂", "cell_bold"), p("High altitude", "cell"), p("Normal", "cell"), p("Improves", "cell"), p("Low inspired PO₂", "cell")],
    ]
    data = [hdr] + rows
    tbl = Table(data, colWidths=[col_w]*5, repeatRows=1)
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), C_TYPE1),
        ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [C_MECH_BG, C_ROW_NORM]),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]))
    return tbl


def build_oxygen_devices():
    col_w = (W - 3*cm) / 4
    hdr = [p("Device", "cell_hdr"), p("FiO₂ Range", "cell_hdr"), p("Flow / Settings", "cell_hdr"), p("Notes", "cell_hdr")]
    rows = [
        [p("Nasal cannula", "cell"), p("24 – 44%\n(~4% per L)", "cell"), p("1 – 6 L/min\n(max 6 L/min)", "cell"), p("Imprecise FiO₂; most comfortable", "cell")],
        [p("Simple face mask", "cell"), p("35 – 55%", "cell"), p("5 – 12 L/min", "cell"), p("Avoid < 5 L (CO₂ rebreathing)", "cell")],
        [p("Venturi mask", "cell"), p("24, 28, 31, 35, 40, 50%", "cell"), p("Variable per valve", "cell"), p("Most precise FiO₂; ideal for COPD", "cell")],
        [p("Non-rebreathing mask", "cell"), p("Up to 80%", "cell"), p("8 – 15 L/min", "cell"), p("One-way valve; high-flow O₂", "cell")],
        [p("HFNC\n(High-flow nasal cannula)", "cell_bold"), p("Up to 100%", "cell"), p("Up to 60 L/min", "cell"), p("Flushes dead space; provides ~PEEP 1-3 cmH₂O; ↓ intubation rate in hypoxaemic failure", "cell")],
    ]
    data = [hdr] + rows
    tbl = Table(data, colWidths=[col_w]*4, repeatRows=1)
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), HexColor("#2C5282")),
        ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [C_ROW_NORM, C_ROW_ALT]),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]))
    return tbl


def build_niv_table():
    col_w = (W - 3*cm) / 4
    hdr = [p("Mode", "cell_hdr"), p("Mechanism", "cell_hdr"), p("Indications", "cell_hdr"), p("Starting Settings", "cell_hdr")]
    rows = [
        [
            p("<b>CPAP</b>", "cell_bold"),
            p("Constant positive airway pressure throughout respiratory cycle; prevents alveolar collapse", "cell"),
            p("Pulmonary oedema, OSA, mild hypoxaemic failure", "cell"),
            p("5 cmH₂O; titrate by 3–5 cmH₂O to max 10–15 cmH₂O", "cell"),
        ],
        [
            p("<b>BiPAP</b>", "cell_bold"),
            p("Higher IPAP on inspiration, lower EPAP on expiration; reduces WOB & assists ventilation", "cell"),
            p("COPD exacerbation, NMJ weakness, weaning, hypercapnic failure", "cell"),
            p("IPAP 10–15 cmH₂O; EPAP 5 cmH₂O; Δ pressure determines ventilation", "cell"),
        ],
    ]
    data = [hdr] + rows
    tbl = Table(data, colWidths=[col_w*0.6, col_w*1.1, col_w*1.1, col_w*1.2], repeatRows=1)
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), HexColor("#2C5282")),
        ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [C_MGMT_BG, C_ROW_NORM]),
        ("TOPPADDING", (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]))
    return tbl


def build_ards_table():
    col_w = (W - 3*cm) / 3
    hdr = [p("Severity", "cell_hdr"), p("PaO₂ / FiO₂ Ratio", "cell_hdr"), p("PEEP Required", "cell_hdr")]
    rows = [
        [p("<b>Mild</b>", "cell_bold"), p("200 – 300 mmHg", "cell"), p("≥ 5 cmH₂O (CPAP)", "cell")],
        [p("<b>Moderate</b>", "cell_bold"), p("100 – 200 mmHg", "cell"), p("≥ 5 cmH₂O", "cell")],
        [p("<b>Severe</b>", "cell_bold"), p("≤ 100 mmHg", "cell"), p("≥ 5 cmH₂O", "cell")],
    ]
    data = [hdr] + rows
    colors_rows = [HexColor("#FEFCBF"), HexColor("#FED7AA"), HexColor("#FEB2B2")]
    tbl = Table(data, colWidths=[col_w]*3, repeatRows=1)
    style = [
        ("BACKGROUND", (0,0), (-1,0), HexColor("#702459")),
        ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
        ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
        ("ALIGN", (0,0), (-1,-1), "CENTER"),
        ("TOPPADDING", (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ]
    for i, c in enumerate(colors_rows):
        style.append(("BACKGROUND", (0, i+1), (-1, i+1), c))
    tbl.setStyle(TableStyle(style))
    return tbl


def build_weaning_criteria():
    items = [
        p("• <b>Oxygenation adequate:</b> PaO₂/FiO₂ > 150–200; PEEP ≤ 5–8 cmH₂O; FiO₂ ≤ 0.4"),
        p("• <b>Haemodynamically stable:</b> no or minimal vasopressors"),
        p("• <b>Initiating condition improving</b>"),
        p("• <b>Adequate respiratory drive:</b> spontaneous breathing effort present"),
        p("• <b>Able to protect airway:</b> cough, gag reflexes intact; follows commands"),
        p("• <b>Spontaneous Breathing Trial (SBT):</b> 30–120 min on PSV 5 / CPAP 5 cmH₂O or T-piece → pass → extubate"),
    ]
    tbl = Table([[i] for i in items], colWidths=[W - 3*cm])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), C_MGMT_BG),
        ("GRID", (0,0), (-1,-1), 0, colors.white),
        ("TOPPADDING", (0,0), (-1,-1), 3),
        ("BOTTOMPADDING", (0,0), (-1,-1), 3),
        ("LEFTPADDING", (0,0), (-1,-1), 8),
    ]))
    return tbl


def build_footer():
    footer_data = [[
        p("Sources: Fishman's Pulmonary Diseases & Disorders (Ch.139)  •  Washington Manual of Medical Therapeutics (pp.276–284)  •  Barash's Clinical Anesthesia 9e (Ch.57)  •  Barash's Clinical Anesthesia 9e (MV section)", "small"),
    ]]
    tbl = Table(footer_data, colWidths=[W - 3*cm])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), HexColor("#EDF2F7")),
        ("TOPPADDING", (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING", (0,0), (-1,-1), 8),
        ("LINEABOVE", (0,0), (-1,0), 0.5, C_FOOTER),
    ]))
    return tbl


# ── Assemble document ────────────────────────────────────────────────────────

def build_document():
    doc = SimpleDocTemplate(
        OUTPUT_PATH,
        pagesize=A4,
        leftMargin=1.5*cm, rightMargin=1.5*cm,
        topMargin=1.5*cm, bottomMargin=1.5*cm,
        title="Respiratory Failure Quick Reference",
        author="Orris Medical AI",
        subject="ICU / Emergency Medicine Quick Reference",
    )

    story = []

    # ── Title block ──
    story.append(build_header_block())
    story.append(sp(8))

    # ── Definition ──
    story.extend(build_definition())

    # ── Types ──
    story.append(KeepTogether([
        section_header("▸  TYPES OF RESPIRATORY FAILURE"),
        sp(4),
        build_types_table(),
        sp(6),
    ]))

    # ── Acute vs Chronic ──
    story.append(KeepTogether([
        section_header("▸  ACUTE vs. CHRONIC"),
        sp(4),
        build_acute_vs_chronic(),
        sp(6),
    ]))

    # ── Mechanisms of Hypoxaemia ──
    story.append(KeepTogether([
        section_header("▸  5 MECHANISMS OF HYPOXAEMIA (Type 1)"),
        sp(4),
        build_hypoxemia_mechanisms(),
        sp(4),
        # Warning box
        Table([[Paragraph(
            "⚠️  <b>Caution (COPD):</b> Supplemental O₂ can worsen V/Q mismatch by reversing hypoxic vasoconstriction. "
            "Target SpO₂ 88–92% to avoid suppressing hypoxic drive and worsening hypercapnia.",
            S["warning"]
        )]], colWidths=[W - 3*cm],
        style=[
            ("BACKGROUND", (0,0), (-1,-1), C_WARN_BG),
            ("BOX", (0,0), (-1,-1), 1, C_WARN_BORDER),
            ("TOPPADDING", (0,0), (-1,-1), 6), ("BOTTOMPADDING", (0,0), (-1,-1), 6),
            ("LEFTPADDING", (0,0), (-1,-1), 8),
        ]),
        sp(6),
    ]))

    # ── Management: O2 devices ──
    story.append(KeepTogether([
        section_header("▸  MANAGEMENT STEP 1 — OXYGEN SUPPLEMENTATION"),
        sp(4),
        build_oxygen_devices(),
        sp(6),
    ]))

    # ── NIV ──
    story.append(KeepTogether([
        section_header("▸  MANAGEMENT STEP 2 — NON-INVASIVE VENTILATION (NPPV)"),
        sp(4),
        build_niv_table(),
        sp(4),
        Table([[Paragraph(
            "✔ <b>NPPV indications:</b> COPD exacerbation, cardiogenic pulmonary oedema, hypoxaemic failure, NMJ weakness, post-extubation.   "
            "✘ <b>Contraindications:</b> inability to protect airway, haemodynamic instability, facial trauma, uncooperative patient.",
            S["body"]
        )]], colWidths=[W - 3*cm],
        style=[
            ("BACKGROUND", (0,0), (-1,-1), HexColor("#F0FFF4")),
            ("BOX", (0,0), (-1,-1), 0.5, HexColor("#68D391")),
            ("TOPPADDING", (0,0), (-1,-1), 6), ("BOTTOMPADDING", (0,0), (-1,-1), 6),
            ("LEFTPADDING", (0,0), (-1,-1), 8),
        ]),
        sp(6),
    ]))

    # ── Invasive MV ──
    story.append(KeepTogether([
        section_header("▸  MANAGEMENT STEP 3 — INVASIVE MECHANICAL VENTILATION"),
        sp(4),
        Table([
            [p("<b>Lung-protective strategy (ARDS/ALI):</b>", "bold"), p("Tidal volume 6 mL/kg IBW  •  Plateau pressure < 30 cmH₂O  •  Optimise PEEP", "cell")],
            [p("<b>Obstructive disease (COPD/Asthma):</b>", "bold"), p("Longer expiratory time  •  Lower RR  •  Watch for auto-PEEP / air trapping", "cell")],
            [p("<b>Neuromuscular disease:</b>", "bold"), p("Assist modes to synchronise with patient effort  •  Early weaning attempts", "cell")],
            [p("<b>Key complications:</b>", "bold"), p("Barotrauma (pneumothorax, pneumomediastinum)  •  ↓ CO (raised intrathoracic pressure)  •  VILI/VALI  •  VAP", "cell")],
        ], colWidths=[(W-3*cm)*0.28, (W-3*cm)*0.72]),
        sp(6),
    ]))

    # ── ARDS ──
    story.append(KeepTogether([
        section_header("▸  ARDS — BERLIN CRITERIA & SEVERITY (Severe form of Type 1)"),
        sp(4),
        p("<b>Berlin Definition:</b> (1) Onset ≤ 1 week of insult; (2) Bilateral opacities on CXR; (3) Not fully explained by cardiac failure/volume overload; (4) PaO₂/FiO₂ ≤ 300 mmHg"),
        sp(4),
        build_ards_table(),
        sp(6),
    ]))

    # ── Weaning ──
    story.append(KeepTogether([
        section_header("▸  WEANING FROM MECHANICAL VENTILATION"),
        sp(4),
        build_weaning_criteria(),
        sp(6),
    ]))

    # ── Quick comparison ──
    story.append(KeepTogether([
        section_header("▸  TYPE 1 vs. TYPE 2 — RAPID COMPARISON"),
        sp(4),
        Table([
            [p("<b>Feature</b>", "cell_hdr"), p("<b>Type 1 (Hypoxaemic)</b>", "cell_hdr"), p("<b>Type 2 (Hypercapnic)</b>", "cell_hdr")],
            [p("Primary defect", "cell"), p("Oxygenation failure", "cell"), p("Ventilatory pump failure", "cell")],
            [p("Key ABG finding", "cell"), p("PaO₂ < 60 mmHg", "cell"), p("PaCO₂ > 45 mmHg; pH < 7.35", "cell")],
            [p("A-a gradient", "cell"), p("Usually ↑ elevated", "cell"), p("Normal (pure pump failure)", "cell")],
            [p("Typical causes", "cell"), p("ARDS, pneumonia, PE, pulmonary oedema", "cell"), p("COPD, asthma, NMJ disease, CNS sedation, OHS", "cell")],
            [p("Best O₂ delivery", "cell"), p("HFNC / CPAP", "cell"), p("Cautious O₂; target SpO₂ 88–92%", "cell")],
            [p("Preferred NIV", "cell"), p("CPAP or HFNC", "cell"), p("BiPAP", "cell")],
        ], colWidths=[(W-3*cm)*0.24, (W-3*cm)*0.38, (W-3*cm)*0.38],
        style=[
            ("BACKGROUND", (0,0), (-1,0), C_HEADER_BG),
            ("GRID", (0,0), (-1,-1), 0.4, C_BORDER),
            ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
            ("ROWBACKGROUNDS", (0,1), (-1,-1), [C_ROW_NORM, C_ROW_ALT]),
            ("TOPPADDING", (0,0), (-1,-1), 5),
            ("BOTTOMPADDING", (0,0), (-1,-1), 5),
            ("LEFTPADDING", (0,0), (-1,-1), 5),
        ]),
        sp(8),
    ]))

    # ── Footer ──
    story.append(build_footer())

    doc.build(story)
    print(f"PDF created: {OUTPUT_PATH}")


if __name__ == "__main__":
    build_document()
Running Command

cd /home/daytona/workspace/respiratory-failure-pdf && python generate_pdf.py 2>&…

Running Command

ls -lh /home/daytona/workspace/respiratory-failure-pdf/Respiratory_Failure_Quick…

Your quick reference PDF is ready:

Respiratory Failure Quick Reference

PDF Document · PDF


What's inside the PDF:
SectionContent
DefinitionWhat respiratory failure is and how it's diagnosed
Types TableAll 5 types (1-4 + Mixed) with criteria, causes, and first-line treatment - colour-coded by type
Acute vs. ChronicKey distinguishing features and ABG patterns
5 Mechanisms of HypoxaemiaV/Q mismatch, shunt, diffusion, hypoventilation, low FiO₂ - with A-a gradient and O₂ response for each
COPD Warning BoxCaution on O₂ delivery in hypercapnic patients
O₂ Delivery DevicesNasal cannula → HFNC with FiO₂ ranges and flow settings
NIV (CPAP/BiPAP)Mechanisms, indications, starting settings, contraindications
Invasive MVLung-protective strategy, obstructive disease tips, complications
ARDS Berlin CriteriaColour-coded severity stratification (mild/moderate/severe)
Weaning CriteriaSBT approach and readiness checklist
Type 1 vs Type 2 ComparisonSide-by-side rapid reference
This is a shared conversation. Sign in to Orris to start your own chat.