I am an MD medicine student. I am preparing for MD final examination. What I want you to do is give me answers to the question I ask from you so that I can use this, use as my source of information for learning and answering the questions that are asked in medical MD medicine final examination. So the first question goes like, how do you approach a case of dyspnea and what is the pathophysiology, differential diagnosis and management of lung abscess?

I am an MD medicine student. I am preparing for MD final examination. What I want you to do is give me answers to the question I ask from you so that I can use this, use as my source of information for learning and answering the questions that are asked in medical MD medicine final examination. So the first question goes like, how do you approach a case of dyspnea and what is the pathophysiology, differential diagnosis and management of lung abscess? and if at last, if you can create a PDF of the answer, it will be of much great help

Reading File
Finding Sources
Finding Sources
Searching PubMed

"lung abscess" AND management

Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/md-medicine-notes && ls /home/daytona/workspace/

I am an MD medicine student. I am preparing for MD final examination. What I want you to do is give me answers to the question I ask from you so that I can use this, use as my source of information for learning and answering the questions that are asked in medical MD medicine final examination. So the first question goes like, how do you approach a case of dyspnea and what is the pathophysiology, differential diagnosis and management of lung abscess? and if at last, if you can create a PDF of the answer, it will be of much great help

Reading File
Finding Sources
Finding Sources
Searching PubMed

"lung abscess" AND management

Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/md-medicine-notes

Writing File

~/md-medicine-notes/create_pdf.py

#!/usr/bin/env python3
"""
MD Medicine Final Exam Notes — PDF Generator
Topic: Approach to Dyspnea + Lung Abscess (Pathophysiology, DDx, Management)
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, ListFlowable, ListItem
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

OUTPUT_PATH = "/home/daytona/workspace/md-medicine-notes/Dyspnea_LungAbscess_MDMedicine.pdf"

# ── Colour palette ─────────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1a3a5c")
MID_BLUE    = colors.HexColor("#2563a8")
LIGHT_BLUE  = colors.HexColor("#dbeafe")
ACCENT_RED  = colors.HexColor("#c0392b")
ACCENT_GRN  = colors.HexColor("#1a7a4a")
ACCENT_ORG  = colors.HexColor("#e67e22")
GREY_BG     = colors.HexColor("#f3f4f6")
GREY_LINE   = colors.HexColor("#d1d5db")
WHITE       = colors.white
BLACK       = colors.black

def make_doc():
    doc = SimpleDocTemplate(
        OUTPUT_PATH,
        pagesize=A4,
        rightMargin=2*cm, leftMargin=2*cm,
        topMargin=2.2*cm, bottomMargin=2.2*cm,
        title="MD Medicine: Dyspnea & Lung Abscess",
        author="Orris AI — Medical Study Notes"
    )
    styles = getSampleStyleSheet()

    # ── Custom styles ──────────────────────────────────────────────────────────
    h_title = ParagraphStyle("h_title", parent=styles["Title"],
        fontSize=22, textColor=DARK_BLUE, spaceAfter=4,
        fontName="Helvetica-Bold", alignment=TA_CENTER, leading=26)

    h_sub = ParagraphStyle("h_sub", parent=styles["Normal"],
        fontSize=11, textColor=MID_BLUE, spaceAfter=14,
        fontName="Helvetica", alignment=TA_CENTER, leading=14)

    h1 = ParagraphStyle("h1", parent=styles["Heading1"],
        fontSize=14, textColor=WHITE, spaceAfter=6, spaceBefore=14,
        fontName="Helvetica-Bold", leading=18,
        backColor=DARK_BLUE, borderPad=6,
        leftIndent=-8, rightIndent=-8)

    h2 = ParagraphStyle("h2", parent=styles["Heading2"],
        fontSize=12, textColor=DARK_BLUE, spaceAfter=4, spaceBefore=10,
        fontName="Helvetica-Bold", leading=16,
        borderPad=(0, 0, 2, 0))

    h3 = ParagraphStyle("h3", parent=styles["Heading3"],
        fontSize=11, textColor=MID_BLUE, spaceAfter=3, spaceBefore=6,
        fontName="Helvetica-BoldOblique", leading=14)

    body = ParagraphStyle("body", parent=styles["Normal"],
        fontSize=10, textColor=BLACK, spaceAfter=5,
        fontName="Helvetica", leading=14, alignment=TA_JUSTIFY)

    bullet = ParagraphStyle("bullet", parent=styles["Normal"],
        fontSize=10, textColor=BLACK, spaceAfter=3,
        fontName="Helvetica", leading=13, leftIndent=14,
        bulletIndent=4, alignment=TA_LEFT)

    note_style = ParagraphStyle("note", parent=styles["Normal"],
        fontSize=9.5, textColor=colors.HexColor("#374151"),
        backColor=LIGHT_BLUE, borderPad=6,
        leftIndent=6, rightIndent=6, spaceAfter=8,
        fontName="Helvetica-Oblique", leading=13)

    warn_style = ParagraphStyle("warn", parent=styles["Normal"],
        fontSize=9.5, textColor=colors.HexColor("#7f1d1d"),
        backColor=colors.HexColor("#fee2e2"), borderPad=6,
        leftIndent=6, rightIndent=6, spaceAfter=8,
        fontName="Helvetica-Bold", leading=13)

    tip_style = ParagraphStyle("tip", parent=styles["Normal"],
        fontSize=9.5, textColor=colors.HexColor("#14532d"),
        backColor=colors.HexColor("#dcfce7"), borderPad=6,
        leftIndent=6, rightIndent=6, spaceAfter=8,
        fontName="Helvetica", leading=13)

    ref_style = ParagraphStyle("ref", parent=styles["Normal"],
        fontSize=8.5, textColor=colors.HexColor("#6b7280"),
        fontName="Helvetica-Oblique", leading=12, spaceAfter=2)

    story = []

    # ══════════════════════════════════════════════════════════════════════════
    # COVER / HEADER
    # ══════════════════════════════════════════════════════════════════════════
    story.append(Spacer(1, 0.5*cm))
    story.append(Paragraph("MD MEDICINE — FINAL EXAMINATION NOTES", h_title))
    story.append(Paragraph(
        "Approach to Dyspnea  |  Lung Abscess: Pathophysiology, Differential Diagnosis & Management",
        h_sub))
    story.append(HRFlowable(width="100%", thickness=2, color=MID_BLUE, spaceAfter=10))
    story.append(Paragraph(
        "<i>Sources: Harrison's Principles of Internal Medicine 22e (2025) · Goldman-Cecil Medicine · "
        "Robbins &amp; Kumar Basic Pathology · Fishman's Pulmonary Diseases and Disorders · "
        "Murray &amp; Nadel's Textbook of Respiratory Medicine</i>",
        ref_style))
    story.append(Spacer(1, 0.3*cm))

    # ══════════════════════════════════════════════════════════════════════════
    # PART 1 — APPROACH TO DYSPNEA
    # ══════════════════════════════════════════════════════════════════════════
    story.append(Paragraph("PART 1 — APPROACH TO A CASE OF DYSPNEA", h1))
    story.append(Spacer(1, 0.2*cm))

    # 1.1 Definition
    story.append(Paragraph("1. Definition", h2))
    story.append(Paragraph(
        "Dyspnea is the sensation of difficult, labored, or <b>unpleasant breathing</b>. "
        "The qualifier 'unpleasant' is critical — labored breathing in a healthy person during exercise "
        "does NOT qualify as dyspnea because it is expected for the degree of exertion. "
        "The physiology of dyspnea remains incompletely understood; multiple afferent neural pathways are "
        "involved, including signals from pulmonary stretch receptors, peripheral/central chemoreceptors, "
        "respiratory muscles, and the cardiovascular system.",
        body))
    story.append(Spacer(1, 0.2*cm))

    # 1.2 Classification
    story.append(Paragraph("2. Classification (First Step in Every Case)", h2))
    story.append(Paragraph(
        "The <b>first clinical question</b> is: <i>Is this dyspnea acute or chronic?</i> "
        "This determines the urgency and differential.",
        body))

    class_data = [
        [Paragraph("<b>Feature</b>", bullet),
         Paragraph("<b>Acute Dyspnea</b>", bullet),
         Paragraph("<b>Chronic Dyspnea</b>", bullet)],
        [Paragraph("Onset", bullet),
         Paragraph("Sudden / minutes–hours", bullet),
         Paragraph("Weeks to months", bullet)],
        [Paragraph("Priority", bullet),
         Paragraph("Rule out life-threatening causes FIRST", bullet),
         Paragraph("Systematic workup for underlying disease", bullet)],
        [Paragraph("Key DDx", bullet),
         Paragraph("PE, pulmonary oedema, pneumothorax, anaphylaxis, pneumonia, acute airway obstruction", bullet),
         Paragraph("COPD, asthma, ILD, heart failure, cardiomyopathy, GERD, hyperventilation", bullet)],
    ]
    class_table = Table(class_data, colWidths=[3.5*cm, 7.5*cm, 7.5*cm])
    class_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("BACKGROUND", (0, 1), (-1, 1), LIGHT_BLUE),
        ("BACKGROUND", (0, 2), (-1, 2), GREY_BG),
        ("BACKGROUND", (0, 3), (-1, 3), LIGHT_BLUE),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.4, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(class_table)
    story.append(Spacer(1, 0.3*cm))

    # 1.3 History
    story.append(Paragraph("3. History Taking", h2))
    story.append(Paragraph("<b>A. Characterise the dyspnea:</b>", h3))
    history_items = [
        "Onset: sudden (pneumothorax, PE) vs. gradual (COPD, heart failure, ILD)",
        "Duration: acute (<72 h), subacute (days–weeks), chronic (>1 month)",
        "Severity: quantify — MRC dyspnoea scale (Grade 1–5), oxygen saturation",
        "Progression: stable, worsening, episodic (asthma, paroxysmal nocturnal dyspnoea)",
        "Precipitating factors: exertion, allergens, posture (orthopnoea → heart failure; platypnoea → AVM/cirrhosis)",
        "Relieving factors: bronchodilators (asthma/COPD), sitting upright (heart failure)",
        "Associated symptoms: cough, wheeze, haemoptysis, fever, chest pain, ankle swelling, palpitations",
        "Positional: orthopnoea, trepopnoea (unilateral lung/pleural disease)",
    ]
    for item in history_items:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    story.append(Paragraph("<b>B. Past medical history &amp; risk factors:</b>", h3))
    risk_items = [
        "Cardiac history: IHD, hypertension, rheumatic heart disease, arrhythmias",
        "Respiratory history: asthma, COPD, TB, recurrent respiratory infections",
        "Smoking history (pack-years) — essential for COPD, lung cancer",
        "Occupational history: asbestos → mesothelioma/asbestosis; silica → silicosis; birds → EAA",
        "Drug history: amiodarone (pulmonary toxicity), methotrexate (ILD), ACE inhibitors (cough-induced dyspnoea)",
        "Travel history: coccidioidomycosis, paragonimiasis, schistosomiasis",
        "Family history: alpha-1 antitrypsin deficiency, cystic fibrosis, pulmonary hypertension",
        "DVT/PE risk: immobility, surgery, OCP, malignancy, long travel",
    ]
    for item in risk_items:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    story.append(Paragraph('<b>"Red Flag" Symptoms — Must Not Be Missed</b>', h3))
    story.append(Paragraph(
        '<font color="#c0392b"><b>⚠ Haemoptysis · Prominent dyspnoea at rest or at night · '
        'Fever with productive cough · Hoarseness · Systemic symptoms (weight loss, night sweats) · '
        'Smoker &gt;45 years with new or changed cough · 30 pack-year history aged 55–80</b></font>',
        warn_style))

    # 1.4 Physical Examination
    story.append(Paragraph("4. Physical Examination", h2))
    pe_data = [
        [Paragraph("<b>System</b>", bullet), Paragraph("<b>Key Findings &amp; Interpretation</b>", bullet)],
        [Paragraph("General", bullet),
         Paragraph("Cyanosis (central vs. peripheral), clubbing (ILD, lung cancer, bronchiectasis, cyanotic CHD), "
                   "pallor (anaemia), cachexia (malignancy/COPD), use of accessory muscles, pursed-lip breathing", bullet)],
        [Paragraph("Vital Signs", bullet),
         Paragraph("RR >25/min → severe respiratory distress; SpO₂ on pulse oximetry; tachycardia; BP (pulsus paradoxus in asthma/tamponade)", bullet)],
        [Paragraph("Neck/JVP", bullet),
         Paragraph("Raised JVP → heart failure, cardiac tamponade, SVC obstruction, cor pulmonale; "
                   "tracheal deviation → pneumothorax (ipsilateral), collapse (contralateral)", bullet)],
        [Paragraph("Chest Inspection", bullet),
         Paragraph("Barrel chest (COPD); asymmetric expansion; Harrison sulcus; kyphoscoliosis", bullet)],
        [Paragraph("Percussion", bullet),
         Paragraph("Dullness → effusion, consolidation, collapse; Hyperresonance → pneumothorax, emphysema", bullet)],
        [Paragraph("Auscultation", bullet),
         Paragraph("Wheeze → asthma, COPD, cardiac asthma; Crepitations → pulmonary oedema (fine basal), "
                   "pneumonia, ILD; Amphoric/cavernous → lung abscess, cavity; Absent breath sounds → "
                   "effusion, pneumothorax; Bronchial breath sounds → consolidation", bullet)],
        [Paragraph("Cardiovascular", bullet),
         Paragraph("S3 gallop, displaced apex → heart failure; loud P2 → pulmonary hypertension; "
                   "murmurs → valvular disease; peripheral oedema", bullet)],
        [Paragraph("Abdomen", bullet),
         Paragraph("Hepatomegaly/ascites → cor pulmonale/right heart failure; hepatosplenomegaly → sarcoidosis", bullet)],
    ]
    pe_table = Table(pe_data, colWidths=[3.5*cm, 15*cm])
    pe_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, GREY_BG]),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.3, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(pe_table)
    story.append(Spacer(1, 0.3*cm))

    # 1.5 Investigations
    story.append(Paragraph("5. Investigations", h2))
    story.append(Paragraph("<b>A. First-Line (All Cases of Unexplained Dyspnoea):</b>", h3))
    inv1 = [
        "<b>Chest X-ray</b> — hyperinflation (COPD/asthma), cardiomegaly (heart failure), infiltrates (pneumonia/ILD), "
        "effusion, pneumothorax, cavitation (lung abscess/TB)",
        "<b>ECG</b> — arrhythmia, LV hypertrophy, right heart strain (PE pattern: S1Q3T3), ischaemia",
        "<b>Arterial Blood Gas (ABG)</b> — type 1 vs type 2 respiratory failure; A-a gradient (PE, ILD); "
        "pH for respiratory/metabolic acidosis",
        "<b>Pulse Oximetry</b> — SpO₂; note: may be falsely normal in anaemia or CO poisoning",
        "<b>Full Blood Count</b> — anaemia, leukocytosis (infection), eosinophilia (asthma/EAA/eosinophilic pneumonia)",
        "<b>Serum BNP/NT-proBNP</b> — <b>extremely helpful</b> in acute dyspnoea to distinguish heart failure from "
        "pulmonary causes (BNP >400 pg/mL → heart failure likely)",
        "<b>Renal/Liver Function, Electrolytes</b> — metabolic causes of dyspnoea, pulmonary-renal syndromes",
    ]
    for item in inv1:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph("<b>B. Second-Line (Guided by History and First-Line Results):</b>", h3))
    inv2 = [
        "<b>Pulmonary Function Tests (PFTs):</b> Spirometry (obstructive vs. restrictive); DLCO (ILD, emphysema, vascular disease); "
        "Flow-volume loops (upper airway obstruction); Methacholine challenge (asthma)",
        "<b>High-Resolution CT Chest (HRCT):</b> Gold standard for ILD; better delineation of cavities, mediastinum, "
        "pulmonary emboli (CTPA), bronchiectasis",
        "<b>Echocardiography:</b> LV/RV function, wall motion abnormalities, valvular disease, pulmonary hypertension, "
        "pericardial effusion — essential when heart failure suspected",
        "<b>CTPA / V/Q Scan:</b> Pulmonary embolism (Wells score guides pre-test probability); D-dimer as screening tool",
        "<b>Point-of-Care Ultrasound (POCUS):</b> Rapidly detects heart failure, pneumonia, PE, pleural effusion, "
        "pneumothorax at bedside — improves sensitivity of standard pathways",
        "<b>6-Minute Walk Test / Cardiopulmonary Exercise Testing (CPET):</b> Quantifies functional capacity; "
        "identifies exercise-induced desaturation and cardiac vs. pulmonary limitation",
        "<b>Bronchoscopy:</b> BAL, biopsy for ILD, endobronchial lesions, haemoptysis workup",
        "<b>Sputum analysis:</b> Gram stain, culture, AFB (TB), cytology (malignancy), eosinophils (EAA)",
        "<b>GERD evaluation:</b> 24-hr oesophageal pH monitoring / modified barium swallow when GERD suspected as cause",
    ]
    for item in inv2:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    story.append(Paragraph(
        "💡 Clinical Tip: BNP testing in acute dyspnoea and POCUS assessment by trained clinicians "
        "improve the sensitivity of standard diagnostic pathways to detect heart failure, pneumonia, PE, "
        "pleural effusion, and pneumothorax (Goldman-Cecil Medicine).",
        tip_style))

    # 1.6 Differential Diagnosis Table
    story.append(Paragraph("6. Differential Diagnosis of Dyspnea — System-Based Approach", h2))

    ddx_data = [
        [Paragraph("<b>System</b>", bullet),
         Paragraph("<b>Common Causes</b>", bullet),
         Paragraph("<b>Distinguishing Features</b>", bullet)],
        # Obstructive
        [Paragraph("<b>Obstructive Airway</b>", bullet),
         Paragraph("Asthma, COPD, bronchiectasis", bullet),
         Paragraph("Expiratory wheeze, prolonged expiratory phase, ↓FEV₁/FVC, reversibility (asthma)", bullet)],
        # Restrictive
        [Paragraph("<b>Restrictive / Parenchymal</b>", bullet),
         Paragraph("ILD, sarcoidosis, pulmonary fibrosis, pneumoconiosis", bullet),
         Paragraph("Bilateral fine crackles, clubbing, ↓TLC, ↓DLCO, HRCT abnormalities", bullet)],
        # Infection
        [Paragraph("<b>Infection</b>", bullet),
         Paragraph("Pneumonia, lung abscess, empyema, TB", bullet),
         Paragraph("Fever, productive cough, consolidation/cavity on CXR, leukocytosis", bullet)],
        # Vascular
        [Paragraph("<b>Vascular</b>", bullet),
         Paragraph("Pulmonary embolism, pulmonary hypertension, AVM", bullet),
         Paragraph("Sudden onset, pleuritic chest pain, S1Q3T3 on ECG, elevated D-dimer, CTPA diagnostic", bullet)],
        # Cardiac
        [Paragraph("<b>Cardiac</b>", bullet),
         Paragraph("Heart failure (LVF), cardiomyopathy, valvular disease, pericardial disease", bullet),
         Paragraph("Orthopnoea, PND, raised JVP, S3 gallop, elevated BNP, cardiomegaly on CXR", bullet)],
        # Pleural
        [Paragraph("<b>Pleural</b>", bullet),
         Paragraph("Pleural effusion, pneumothorax, mesothelioma", bullet),
         Paragraph("Reduced breath sounds, stony dullness (effusion), hyperresonance (pneumothorax), "
                   "tracheal deviation (tension PTX)", bullet)],
        # Upper airway
        [Paragraph("<b>Upper Airway</b>", bullet),
         Paragraph("Epiglottitis, anaphylaxis, foreign body, VCD", bullet),
         Paragraph("Stridor (inspiratory), acute onset, variable extrathoracic obstruction on flow-volume loop", bullet)],
        # Metabolic/Systemic
        [Paragraph("<b>Metabolic / Systemic</b>", bullet),
         Paragraph("Severe anaemia, metabolic acidosis, thyrotoxicosis, obesity hypoventilation", bullet),
         Paragraph("No primary lung/cardiac findings; anaemia (pallor, ↓Hb); Kussmaul breathing (DKA)", bullet)],
        # Neuromuscular
        [Paragraph("<b>Neuromuscular</b>", bullet),
         Paragraph("MND, Guillain-Barré, myasthenia gravis, diaphragm palsy", bullet),
         Paragraph("Paradoxical breathing, ↓MIP, orthopnoea when lying flat (diaphragm weakness)", bullet)],
        # Psychogenic
        [Paragraph("<b>Psychogenic</b>", bullet),
         Paragraph("Hyperventilation syndrome, panic disorder, VCD", bullet),
         Paragraph("Perioral tingling, Chvostek's sign (respiratory alkalosis), normal investigations", bullet)],
    ]
    ddx_table = Table(ddx_data, colWidths=[4*cm, 5.5*cm, 9*cm])
    ddx_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, GREY_BG]),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.3, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(ddx_table)
    story.append(Spacer(1, 0.3*cm))

    # 1.7 Management Framework
    story.append(Paragraph("7. Management Framework for Dyspnea", h2))
    story.append(Paragraph(
        "Management is <b>aetiology-directed</b>. However, the immediate priority is stabilisation:",
        body))
    mgmt_items = [
        "<b>Immediate:</b> Airway (position, oxygen therapy titrated to SpO₂ 94–98%; 88–92% in COPD), "
        "IV access, continuous monitoring (ECG, SpO₂, RR, BP)",
        "<b>Assess severity:</b> Clinical signs of impending respiratory failure → early NIV/intubation decision",
        "<b>Treat the underlying cause:</b> Bronchodilators (asthma/COPD) · Diuretics + nitrates (acute LVF) · "
        "Antibiotics (pneumonia/abscess) · Anticoagulation (PE) · Pleural drainage (effusion/pneumothorax)",
        "<b>Oxygen delivery:</b> Nasal prongs → Venturi mask → Non-rebreather mask → High-flow nasal oxygen (HFNO) → "
        "NIV (CPAP/BiPAP) → Intubation and mechanical ventilation",
        "<b>Supportive:</b> Posture (sitting upright); physiotherapy; smoking cessation; pulmonary rehabilitation (chronic)",
        "<b>Refractory dyspnoea:</b> Despite maximally treated chronic heart and lung disease — judicious opioids "
        "(oral morphine) can reduce the sensation of air hunger (Goldman-Cecil Medicine)",
        "<b>Multiple causes:</b> Since dyspnoea may result simultaneously from more than one condition, "
        "maintain all partially effective treatments while adding disease-specific therapy",
    ]
    for item in mgmt_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # PART 2 — LUNG ABSCESS
    # ══════════════════════════════════════════════════════════════════════════
    story.append(Paragraph("PART 2 — LUNG ABSCESS", h1))
    story.append(Spacer(1, 0.2*cm))

    # 2.1 Definition & Classification
    story.append(Paragraph("1. Definition", h2))
    story.append(Paragraph(
        "A <b>lung abscess</b> is a localised area of suppuration (necrosis and cavitation) within the pulmonary "
        "parenchyma, resulting in the formation of one or more cavities, usually a single dominant cavity "
        "<b>&gt;2 cm in diameter</b>. (Harrison's, 22e)",
        body))
    story.append(Spacer(1, 0.2*cm))

    story.append(Paragraph("2. Classification", h2))
    class2_data = [
        [Paragraph("<b>Parameter</b>", bullet),
         Paragraph("<b>Type A</b>", bullet),
         Paragraph("<b>Type B</b>", bullet)],
        [Paragraph("By Duration", bullet),
         Paragraph("<b>Acute</b>: &lt;4–6 weeks", bullet),
         Paragraph("<b>Chronic</b>: &gt;6 weeks (~40% of cases)", bullet)],
        [Paragraph("By Aetiology", bullet),
         Paragraph("<b>Primary</b> (~80%): aspiration in normal host; anaerobic organisms; "
                   "no underlying pulmonary/systemic disease", bullet),
         Paragraph("<b>Secondary</b> (~20%): underlying condition — obstruction (tumour, FB), "
                   "systemic disease (HIV, immunosuppression), haematogenous spread", bullet)],
        [Paragraph("By Smell", bullet),
         Paragraph("<b>Putrid</b>: foul-smelling sputum — virtually diagnostic of anaerobic abscess", bullet),
         Paragraph("<b>Non-putrid</b>: aerobic or mixed organisms", bullet)],
    ]
    class2_table = Table(class2_data, colWidths=[4*cm, 8*cm, 6.5*cm])
    class2_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, GREY_BG, WHITE]),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.3, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(class2_table)
    story.append(Spacer(1, 0.3*cm))

    # 2.2 Etiology / Risk Factors
    story.append(Paragraph("3. Etiology and Risk Factors", h2))
    story.append(Paragraph("<b>A. Mechanisms of Organism Entry:</b>", h3))
    etiol_items = [
        "<b>Aspiration</b> (most common) — infective material from carious teeth, infected sinuses/tonsils, "
        "gastric contents; occurs during anaesthesia, coma, alcoholic intoxication, seizures, bulbar dysfunction, "
        "neuromuscular disease, oesophageal dysmotility, GORD",
        "<b>Complication of necrotising pneumonia</b> — S. aureus, Streptococcus pyogenes, Klebsiella pneumoniae, "
        "Pseudomonas spp., rarely type 3 Pneumococcus",
        "<b>Bronchial obstruction</b> — lung cancer, foreign body; distal atelectasis → impaired drainage → abscess",
        "<b>Septic emboli</b> — right-sided infective endocarditis (tricuspid valve, commonly S. aureus); "
        "Lemierre's syndrome (Fusobacterium necrophorum — pharyngeal infection → jugular septic thrombophlebitis → lung)",
        "<b>Haematogenous spread</b> — staphylococcal bacteraemia → multiple abscesses",
        "<b>Spread from sub-diaphragmatic infection</b> — amoebic liver abscess (Entamoeba histolytica) "
        "→ right lower lobe basal abscess via trans-diaphragmatic spread",
    ]
    for item in etiol_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph("<b>B. Host Risk Factors for Aspiration:</b>", h3))
    risk2_items = [
        "Altered mental status — alcohol, drug overdose, general anaesthesia, seizures, head trauma",
        "Neurological disease — stroke, bulbar palsy, neuromuscular disease, Parkinson's disease",
        "Oesophageal disease — dysmotility, strictures, tumours, GORD, Zenker's diverticulum",
        "Poor dental hygiene — periodontal disease, gingivitis (colonisation with oral anaerobes)",
        "Immunocompromised states — HIV, organ transplant, haematological malignancy (→ secondary abscess)",
    ]
    for item in risk2_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph(
        "📌 Key Fact: Many physicians consider it extremely rare for lung abscesses to develop "
        "in the absence of teeth, as the gingival crevices act as the nidus for anaerobic colonisation. "
        "In edentulous patients, always suspect an obstructing endobronchial lesion, PE, or septic embolus. "
        "(Fishman's Pulmonary Diseases)",
        note_style))

    # 2.3 Microbiology
    story.append(Paragraph("4. Microbiology", h2))
    micro_data = [
        [Paragraph("<b>Clinical Scenario</b>", bullet), Paragraph("<b>Key Pathogens</b>", bullet)],
        [Paragraph("Primary (aspiration) lung abscess", bullet),
         Paragraph("Anaerobes: Prevotella spp., Fusobacterium spp., Bacteroides spp., "
                   "Peptostreptococcus spp., microaerophilic streptococci (milleri group)\n"
                   "Note: Anaerobes recoverable in up to 93% of cases; present as sole isolate in 46%", bullet)],
        [Paragraph("Secondary abscess (immunocompromised)", bullet),
         Paragraph("S. aureus (MSSA/MRSA), Gram-negative rods (Pseudomonas aeruginosa, Enterobacteriaceae, "
                   "Klebsiella), Nocardia, Aspergillus, Mucorales, Cryptococcus, Legionella, "
                   "Rhodococcus equi, PCP (Pneumocystis jirovecii)", bullet)],
        [Paragraph("Septic emboli", bullet),
         Paragraph("S. aureus (from endocarditis), Fusobacterium necrophorum (Lemierre's syndrome)", bullet)],
        [Paragraph("Endemic infections", bullet),
         Paragraph("MTB, MAC, M. kansasii; Coccidioides, Histoplasma, Blastomyces; "
                   "Entamoeba histolytica, Paragonimus westermani, Echinococcus (hydatid)", bullet)],
        [Paragraph("Post-viral", bullet),
         Paragraph("S. aureus superinfection after influenza; also Actinomyces spp.", bullet)],
        [Paragraph("Hospital-acquired / nosocomial", bullet),
         Paragraph("Gram-negative organisms with resistance patterns — Klebsiella, Pseudomonas, E. coli, "
                   "Enterobacter; MRSA", bullet)],
    ]
    micro_table = Table(micro_data, colWidths=[5*cm, 13.5*cm])
    micro_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, GREY_BG, WHITE, GREY_BG, WHITE, GREY_BG]),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.3, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(micro_table)
    story.append(Spacer(1, 0.3*cm))

    # 2.4 Pathophysiology
    story.append(Paragraph("5. Pathophysiology", h2))

    story.append(Paragraph("<b>Step-by-Step Pathogenesis (Primary Lung Abscess):</b>", h3))
    patho_steps = [
        "<b>Step 1 — Aspiration:</b> Oropharyngeal/gastric contents (laden with anaerobes and microaerophilic "
        "streptococci) are aspirated into the dependent lung segments — posteriorly when supine.",
        "<b>Step 2 — Insufficient Clearance:</b> The patient carries an overwhelming burden of aspirated material "
        "or is unable to clear the bacterial load (due to impaired mucociliary clearance, cough reflex, or phagocytic function).",
        "<b>Step 3 — Pneumonitis (Days 1–7):</b> Aspiration produces an initial chemical pneumonitis (partly from "
        "gastric acid injury), followed by bacterial inflammation. The polymicrobial flora, with synergistic "
        "virulence factors, begins tissue destruction.",
        "<b>Step 4 — Parenchymal Necrosis (Days 7–14):</b> Anaerobes with their synergistic virulence cause "
        "progressive liquefactive necrosis of lung parenchyma. The cavity forms over 1–2 weeks.",
        "<b>Step 5 — Cavitation:</b> As the necrotic focus enlarges, it ruptures into an adjacent airway. "
        "Partial drainage produces the characteristic air-fluid level on CXR. The cavity may become lined "
        "with regenerated epithelium.",
        "<b>Step 6 — Complications:</b> If untreated: extension to pleural space (empyema/bronchopleural fistula), "
        "pneumothorax, haematogenous spread to brain (cerebral abscess, meningitis), massive haemoptysis, "
        "or development of chronic lung abscess with surrounding bronchiectasis.",
    ]
    for i, step in enumerate(patho_steps):
        story.append(Paragraph(step, bullet))
        story.append(Spacer(1, 0.15*cm))

    story.append(Paragraph("<b>Location (Dependent on Mechanism):</b>", h3))
    loc_items = [
        "<b>Aspiration in recumbent position</b> → <b>Posterior segment of right upper lobe</b> and "
        "<b>apical segments of lower lobes</b> (right &gt; left; right mainstem bronchus less angulated)",
        "<b>Aspiration in upright/sitting position</b> → Basal segments of lower lobes",
        "<b>Necrotising pneumonia / bronchiectasis</b> → Multiple, basal, scattered",
        "<b>Haematogenous / septic emboli</b> → Multiple, any location, bilateral",
        "<b>Amoebic liver abscess spread</b> → Right lower lobe, basal (posterior segment)",
    ]
    for item in loc_items:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    story.append(Paragraph("<b>Morphology (Robbins &amp; Kumar):</b>", h3))
    story.append(Paragraph(
        "Abscesses range from a few mm to 5–6 cm. As suppuration enlarges, the abscess ruptures into airways "
        "→ air-fluid level on imaging. Occasionally ruptures into pleural cavity → bronchopleural fistula → "
        "pneumothorax / empyema. Septic material may embolise to brain → meningitis or cerebral abscess. "
        "Surrounding lung: local bronchial obstruction → bronchiectasis or emphysema in adjacent areas.",
        body))

    # 2.5 Clinical Features
    story.append(Paragraph("6. Clinical Features", h2))
    story.append(Paragraph("<b>Symptoms:</b>", h3))
    sym_items = [
        "Fever, cough, sputum production, chest pain (pleuritic if pleural involvement) — initially similar to pneumonia",
        "<b>Anaerobic abscess:</b> More chronic/indolent — fever, night sweats, weight loss, fatigue, anaemia (hallmarks)",
        "<b>Putrid abscess (anaerobic):</b> Foul-smelling, foul-tasting sputum / expectoration of large amounts of "
        "purulent sputum — virtually pathognomonic of anaerobic infection",
        "<b>Non-anaerobic (e.g., S. aureus):</b> More fulminant — high fevers, rapid progression",
        "Haemoptysis — may be massive (life-threatening complication)",
        "Dyspnoea — variable; worse with large abscess, complications, or underlying lung disease",
    ]
    for item in sym_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph("<b>Signs:</b>", h3))
    sign_items = [
        "Fever (may be high/remittent), tachycardia, tachypnoea",
        "Poor dentition / gingival disease — important clue to aspiration aetiology",
        "<b>Amphoric/cavernous breath sounds</b> on auscultation (hallmark of large cavity)",
        "Signs of consolidation (dullness, bronchial breathing) in surrounding area",
        "Digital clubbing — in chronic/long-standing cases",
        "Absent gag reflex — indicates ongoing aspiration risk",
        "Weight loss, pallor, signs of anaemia — in chronic abscess",
    ]
    for item in sign_items:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    # 2.6 Differential Diagnosis
    story.append(Paragraph("7. Differential Diagnosis — Cavitary Lung Lesions", h2))
    story.append(Paragraph(
        "The differential of a cavitary lung lesion is broad. The mnemonic <b>CAVITY</b> is useful:",
        body))

    story.append(Paragraph(
        "C — Carcinoma (squamous cell carcinoma most commonly cavitates; also sarcoma)\n"
        "A — Abscess (bacterial — typical/atypical) | Autoimmune vasculitis (GPA/Wegener's)\n"
        "V — Vascular (pulmonary infarct, septic emboli from endocarditis, AVM)\n"
        "I — Infection: TB (most common worldwide), NTM, Histoplasma, Coccidioides, Aspergillus, Mucor, Nocardia, Actinomyces, Entamoeba histolytica, Paragonimus\n"
        "T — Trauma (haematoma with secondary necrosis)\n"
        "Y — Young cysts (bronchogenic cysts, bullae, sequestration with infection)",
        note_style))

    ddx2_data = [
        [Paragraph("<b>Condition</b>", bullet),
         Paragraph("<b>Distinguishing Features</b>", bullet)],
        [Paragraph("Pulmonary TB", bullet),
         Paragraph("Upper lobe cavitation, AFB smear/culture, Mantoux/IGRA positive, contact history, "
                   "lymphadenopathy, constitutional symptoms, thin-walled cavity; "
                   "may have satellite lesions and tree-in-bud pattern on CT", bullet)],
        [Paragraph("Primary Lung Cancer (SCC)", bullet),
         Paragraph("Thick irregular wall, eccentric cavity, lobulated/spiculated margins on CT; "
                   "smoking history, age >50, weight loss; PET/biopsy confirms; "
                   "absence of fever/leukocytosis (unless superinfected)", bullet)],
        [Paragraph("Pulmonary Embolism with Infarction", bullet),
         Paragraph("Hampton's hump on CXR, pleural-based wedge opacity, no fever initially, "
                   "elevated D-dimer, CTPA diagnostic; cavity may form if infarct becomes necrotic", bullet)],
        [Paragraph("Septic Emboli / Endocarditis", bullet),
         Paragraph("Multiple bilateral peripheral cavities, IV drug use, cardiac murmur, "
                   "positive blood cultures (S. aureus), echocardiography shows vegetations; "
                   "Lemierre's: jugular vein thrombosis + pharyngitis prodrome", bullet)],
        [Paragraph("Granulomatosis with Polyangiitis (GPA)", bullet),
         Paragraph("Bilateral cavitary nodules + renal involvement (haematuria/proteinuria) + "
                   "upper airway disease; c-ANCA/PR3-ANCA positive; biopsy: necrotising granulomatous vasculitis", bullet)],
        [Paragraph("Fungal Infections (Aspergillus, Mucor, Histoplasma)", bullet),
         Paragraph("Immunocompromised host (neutropenia, transplant, DM); "
                   "Aspergilloma: fungal ball in pre-existing cavity, air-crescent sign on CT; "
                   "Mucor: rapidly progressive, black eschar, angioinvasion; serum galactomannan", bullet)],
        [Paragraph("Amoebic Lung Abscess", bullet),
         Paragraph("Travel to endemic area, right lower lobe basal location, "
                   "'chocolate sauce' sputum (anchovy paste), concurrent liver abscess on USG/CT, "
                   "amoeba serology; responds to metronidazole", bullet)],
        [Paragraph("Hydatid Cyst (Echinococcus)", bullet),
         Paragraph("Sheep-rearing area, 'water lily sign' on CXR/CT (floating membranes), "
                   "serological tests, eosinophilia; rupture → anaphylaxis risk", bullet)],
        [Paragraph("Cryptogenic Organising Pneumonia (COP)", bullet),
         Paragraph("Bilateral, migratory infiltrates ± cavitation; does not respond to antibiotics; "
                   "responds dramatically to corticosteroids; BAL shows organising pneumonia pattern", bullet)],
        [Paragraph("Pulmonary Sequestration", bullet),
         Paragraph("Non-functioning lung tissue with aberrant arterial supply; "
                   "recurrent pneumonia in same location; CT angiography diagnostic; "
                   "intralobar (no separate pleura) vs. extralobar", bullet)],
    ]
    ddx2_table = Table(ddx2_data, colWidths=[5*cm, 13.5*cm])
    ddx2_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, GREY_BG] * 6),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.3, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(ddx2_table)
    story.append(Spacer(1, 0.3*cm))

    story.append(Paragraph(
        "⚠ Exam Point: Lung abscess (infectious) is distinguished from cavitating carcinoma by: "
        "fever + leukocytosis in abscess; thick irregular eccentric wall in carcinoma (though overlap exists); "
        "always biopsy/bronchoscope if no response to 6 weeks of antibiotics to exclude malignancy.",
        warn_style))

    # 2.7 Diagnosis / Investigations
    story.append(Paragraph("8. Diagnosis and Investigations", h2))

    story.append(Paragraph("<b>A. Imaging:</b>", h3))
    img_items = [
        "<b>Chest X-ray (CXR):</b> Thick-walled cavity with air-fluid level — classic finding. "
        "Usually in posterior segment of RUL or apical segments of lower lobes. "
        "Useful to identify complications (effusion, empyema, pneumothorax)",
        "<b>CT Chest (preferred):</b> Better definition of cavity size, wall thickness, contents; "
        "earlier evidence of cavitation than CXR; identifies surrounding lung pathology (atelectasis, "
        "bronchiectasis); distinguishes lung abscess from empyema (important — affects management); "
        "may reveal underlying obstructing mass/tumour",
        "<b>POCUS (Point-of-Care Ultrasound):</b> Can identify peripheral abscess, adjacent pleural fluid; "
        "increasingly used at bedside for rapid assessment (2025 evidence — Porcel et al., Med Clin 2025)",
    ]
    for item in img_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph("<b>B. Microbiological Investigations:</b>", h3))
    micro_inv = [
        "<b>Sputum:</b> Gram's stain, culture — noninvasive; limited due to oropharyngeal contamination; "
        "culture may not reflect anaerobes; still recommended as first step",
        "<b>Blood cultures:</b> Yield pathogen in secondary abscesses / systemic sepsis",
        "<b>Bronchoscopy with BAL / protected brush specimen:</b> When secondary abscess suspected or "
        "empirical therapy fails; risk: aspiration of abscess contents into contralateral lung",
        "<b>CT-guided percutaneous needle aspiration:</b> When above methods fail; "
        "risks: pneumothorax, bronchopleural fistula, seeding of pleural space",
        "<b>Sputum smell:</b> Putrid odour = virtually diagnostic of anaerobic lung abscess",
        "<b>Emerging:</b> Molecular techniques (16S rRNA gene amplification) for improved pathogen ID",
        "<b>Serology:</b> Amoeba serology (ELISA), Aspergillus galactomannan, fungal cultures — "
        "in immunocompromised patients or failed empirical therapy",
    ]
    for item in micro_inv:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph("<b>C. Other Investigations:</b>", h3))
    other_inv = [
        "CBC: leukocytosis (bacterial), eosinophilia (parasitic/fungal), anaemia (chronic infection)",
        "CRP/ESR: elevated — non-specific markers of infection/inflammation",
        "LFTs + serum albumin: hypoalbuminaemia in chronic abscess; LFT abnormalities → amoebic liver abscess",
        "AFB smear and culture (3 samples): Exclude TB — always in endemic areas",
        "Bronchoscopy: essential to exclude endobronchial obstruction (tumour, foreign body) — "
        "especially in non-resolving, non-aspirating abscess or edentulous patient",
        "PET-CT / tissue biopsy: When malignancy cannot be excluded",
    ]
    for item in other_inv:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    # 2.8 MANAGEMENT
    story.append(Paragraph("9. Management of Lung Abscess", h2))
    story.append(Paragraph(
        "Management includes <b>antibiotics</b> (primary), <b>postural drainage</b>, and "
        "<b>interventional procedures</b> when needed. Surgery is a last resort.",
        body))

    story.append(Paragraph("<b>A. Antibiotic Therapy (Primary Treatment):</b>", h3))
    story.append(Paragraph(
        "Antibiotics established themselves as the primary treatment in the 1940–1950s, largely replacing surgery. "
        "For many decades penicillin was standard; however, because oral anaerobes produce β-lactamases, "
        "<b>clindamycin has proved superior to penicillin in clinical trials.</b> (Harrison's 22e)",
        body))

    abx_data = [
        [Paragraph("<b>Scenario</b>", bullet),
         Paragraph("<b>First-Line Regimen</b>", bullet),
         Paragraph("<b>Duration</b>", bullet)],
        [Paragraph("<b>Primary Lung Abscess</b>\n(aspiration, anaerobic)", bullet),
         Paragraph(
             "Option 1: <b>Clindamycin</b> 600 mg IV TDS → (on improvement) 300 mg PO QDS\n\n"
             "Option 2: <b>IV β-lactam/β-lactamase inhibitor</b> (e.g., ampicillin-sulbactam, "
             "piperacillin-tazobactam) → <b>Amoxicillin-clavulanate PO</b> once stable\n\n"
             "Alternative: <b>Moxifloxacin</b> 400 mg/day PO (small study: comparable to ampicillin-sulbactam)\n\n"
             "<font color='#c0392b'>⚠ Metronidazole ALONE is NOT adequate — does not cover microaerophilic streptococci</font>",
             bullet),
         Paragraph("3–14 weeks (until imaging shows clearance or small scar).\n\n"
                   "≥6 weeks associated with better outcomes.", bullet)],
        [Paragraph("<b>Secondary Lung Abscess</b>\n(immunocompromised / identified pathogen)", bullet),
         Paragraph("Target therapy based on identified pathogen (cultures essential).\n\n"
                   "Broad coverage for Gram-negatives (including Pseudomonas): Piperacillin-tazobactam, "
                   "carbapenems (meropenem/imipenem) ± anti-MRSA agent (vancomycin/linezolid) if MRSA suspected.\n\n"
                   "Treat underlying condition (relieve obstruction, treat immunosuppression cause).", bullet),
         Paragraph("Until imaging confirms abscess resolution (prolonged — variable).", bullet)],
        [Paragraph("<b>TB / Atypical Mycobacteria</b>", bullet),
         Paragraph("Standard anti-TB regimen (2HRZE/4HR); NTM — per species-specific protocol", bullet),
         Paragraph("TB: 6 months (or longer for drug-resistant TB)", bullet)],
        [Paragraph("<b>Amoebic Lung Abscess</b>", bullet),
         Paragraph("<b>Metronidazole</b> 500–750 mg TDS × 7–10 days + luminal agent (diloxanide furoate)", bullet),
         Paragraph("10–14 days", bullet)],
        [Paragraph("<b>Fungal (Aspergillus)</b>", bullet),
         Paragraph("Voriconazole (first line); Amphotericin B (alternative)\nMucor: Amphotericin B + surgery", bullet),
         Paragraph("Prolonged (weeks to months)", bullet)],
    ]
    abx_table = Table(abx_data, colWidths=[4*cm, 10.5*cm, 4*cm])
    abx_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, GREY_BG, WHITE, GREY_BG, WHITE]),
        ("BOX", (0, 0), (-1, -1), 0.5, GREY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.3, GREY_LINE),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(abx_table)
    story.append(Spacer(1, 0.3*cm))

    story.append(Paragraph("<b>B. Supportive Measures:</b>", h3))
    supp_items = [
        "<b>Postural drainage</b> — physiotherapy, positioning to facilitate drainage through the airway",
        "<b>Adequate nutrition</b> — high-protein diet; nutritional support in malnourished/chronic cases",
        "<b>Oxygen therapy</b> if hypoxic",
        "<b>Treat aspiration risk</b> — oral hygiene, dental care (reduces anaerobic burden), elevate head of bed, "
        "PPI for GORD, address swallowing dysfunction (SLP assessment)",
        "<b>Hydration</b> and management of fever/sepsis",
    ]
    for item in supp_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Paragraph("<b>C. When Antibiotics Fail — Interventional Options:</b>", h3))
    story.append(Paragraph(
        "As many as <b>10–20% of patients</b> do not respond to antibiotics, with continued fevers and "
        "progression of abscess cavity on imaging. An abscess <b>&gt;6–8 cm</b> is less likely to respond to "
        "antibiotics alone. (Harrison's 22e)",
        body))
    interv_items = [
        "<b>Reassess diagnosis</b> — repeat CT, bronchoscopy (exclude malignancy, FB, unusual pathogen); "
        "additional cultures/serology",
        "<b>Percutaneous CT-guided drainage</b> — for patients who fail antibiotics and are poor surgical candidates; "
        "complications: bacterial contamination of pleural space, pneumothorax, haemothorax; "
        "risk increased if traversing normal lung parenchyma (Hadid et al., J Thorac Dis 2024)",
        "<b>Bronchoscopic drainage / endobronchial aspiration</b> — can facilitate drainage and allow culture",
        "<b>Surgical resection (lobectomy)</b> — definitive treatment for persistent, non-responsive abscess; "
        "also for life-threatening haemoptysis; goal: balance procedural morbidity vs. need to clear infection; "
        "drainage should be present (not active) at time of surgery to reduce contamination risk",
    ]
    for item in interv_items:
        story.append(Paragraph(f"• {item}", bullet))

    # 2.9 Complications
    story.append(Paragraph("10. Complications", h2))
    comp_items = [
        "<b>Empyema thoracis</b> — extension to pleural space (most common serious complication); "
        "requires urgent intercostal drain + antibiotics",
        "<b>Bronchopleural fistula</b> — communication between bronchial tree and pleural space; "
        "pyopneumothorax; difficult to manage",
        "<b>Life-threatening haemoptysis</b> — erosion of pulmonary vessel wall; "
        "may require bronchial artery embolisation or emergency surgery",
        "<b>Cerebral abscess / Meningitis</b> — haematogenous spread of septic emboli to CNS",
        "<b>Bacteraemia / Septicaemia</b> — systemic spread; septic shock",
        "<b>Chronic lung abscess</b> — persistent cavity >6 weeks; "
        "associated bronchiectasis, recurrent infection, amyloidosis (long-standing)",
        "<b>Pneumatocele formation</b> — persistent cystic changes; "
        "larger cavity size on presentation correlates with pneumatocele and bronchiectasis development",
        "<b>Contralateral lung spillage</b> — during bronchoscopy or posture changes; "
        "aspiration of abscess contents → widespread necrotising pneumonia",
        "<b>Respiratory failure</b> — in severe/bilateral disease or with underlying lung compromise",
    ]
    for item in comp_items:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    # 2.10 Prognosis
    story.append(Paragraph("11. Prognosis and Poor Prognostic Factors", h2))
    story.append(Paragraph(
        "With appropriate antibiotic therapy, <b>primary lung abscess mortality can be as low as 2%</b>. "
        "Secondary lung abscess has significantly higher mortality — <b>up to 75%</b> in some case series.",
        body))
    prog_items = [
        "Age >60 years",
        "Malignancy-related abscess",
        "Presence of aerobic bacteria (non-anaerobic abscess)",
        "Sepsis at presentation",
        "Symptom duration >8 weeks",
        "Abscess size >6 cm",
        "Immunocompromised state",
        "Secondary lung abscess (underlying condition)",
    ]
    story.append(Paragraph("<b>Poor Prognostic Factors:</b>", h3))
    for item in prog_items:
        story.append(Paragraph(f"• {item}", bullet))
    story.append(Spacer(1, 0.2*cm))

    # 2.11 Prevention
    story.append(Paragraph("12. Prevention", h2))
    prev_items = [
        "Address aspiration risk: airway protection (cuffed ET tube during anaesthesia), correct positioning",
        "Oral hygiene and dental care — reduces colonisation of gingival crevices with anaerobes",
        "Prophylactic antibiotics in high-risk aspiration (selected cases)",
        "Management of underlying risk factors (alcohol, seizures, GORD, dysphagia)",
        "Early and appropriate antibiotic treatment of necrotising pneumonia",
        "Bronchoscopy to relieve endobronchial obstruction (foreign body, tumour)",
    ]
    for item in prev_items:
        story.append(Paragraph(f"• {item}", bullet))

    story.append(Spacer(1, 0.4*cm))
    story.append(HRFlowable(width="100%", thickness=1.5, color=MID_BLUE, spaceAfter=10))

    # ── QUICK REVISION SUMMARY BOX ──────────────────────────────────────────
    story.append(Paragraph("QUICK REVISION — HIGH-YIELD EXAM POINTS", h1))
    story.append(Spacer(1, 0.2*cm))

    qr_items = [
        "<b>Dyspnea definition:</b> Sensation of difficult, labored, or UNPLEASANT breathing — "
        "'unpleasant' is key because normal exertional breathlessness is excluded.",
        "<b>BNP in acute dyspnoea:</b> Extremely helpful — distinguishes heart failure from pulmonary causes "
        "(BNP >400 pg/mL favours heart failure).",
        "<b>Lung abscess definition:</b> Necrosis + cavitation of lung by microbial infection; "
        "usually single dominant cavity >2 cm.",
        "<b>Most common aetiology:</b> Aspiration of anaerobes from gingival crevices — "
        "right side > left; posterior segment RUL and apical segments of lower lobes.",
        "<b>Microbiology:</b> Anaerobes in up to 93%; polymicrobial most common. "
        "Putrid sputum = virtually diagnostic of anaerobic abscess.",
        "<b>Cavitation on CXR:</b> Air-fluid level in thick-walled cavity — takes 1–2 weeks to form.",
        "<b>1st-line treatment:</b> Clindamycin IV → PO (superior to penicillin because β-lactamase-producing anaerobes).",
        "<b>Metronidazole alone = INADEQUATE</b> — does not cover microaerophilic streptococci.",
        "<b>Duration:</b> Until imaging resolution — minimum 3–4 weeks, often 6–14 weeks.",
        "<b>Failure indicators:</b> No response in 7 days; abscess >6–8 cm; ongoing fever/progression "
        "→ reassess diagnosis, consider drainage, consider surgical resection.",
        "<b>Lemierre's syndrome:</b> Fusobacterium necrophorum → pharyngitis → jugular vein septic thrombophlebitis "
        "→ septic pulmonary emboli → multiple cavitary lung lesions.",
        "<b>In edentulous patients with lung abscess:</b> Always suspect underlying obstructing endobronchial lesion "
        "— bronchoscopy is mandatory.",
        "<b>Amoebic abscess:</b> Right lower lobe, basal; chocolate-sauce sputum; associated liver abscess; "
        "treat with metronidazole.",
        "<b>Prognosis:</b> Primary abscess mortality ~2%; secondary abscess up to 75%. "
        "Poor factors: age >60, malignancy, size >6 cm, aerobic bacteria, sepsis at presentation.",
    ]
    for i, item in enumerate(qr_items):
        bg = LIGHT_BLUE if i % 2 == 0 else colors.HexColor("#f0f9ff")
        qr_style = ParagraphStyle(f"qr_{i}", parent=body,
            backColor=bg, leftIndent=8, rightIndent=4,
            borderPad=5, spaceAfter=4, leading=14)
        story.append(Paragraph(f"{'●'} {item}", qr_style))

    story.append(Spacer(1, 0.5*cm))
    story.append(HRFlowable(width="100%", thickness=1, color=GREY_LINE, spaceAfter=6))
    story.append(Paragraph(
        "<b>References:</b> Harrison's Principles of Internal Medicine 22e (2025, McGraw-Hill) · "
        "Goldman-Cecil Medicine, International Edition · Robbins &amp; Kumar Basic Pathology · "
        "Fishman's Pulmonary Diseases and Disorders, 2-Volume Set · "
        "Hadid W et al. Lung abscess: the non-conservative management — a narrative review. "
        "J Thorac Dis. 2024 [PMID: 38883669] · "
        "Porcel JM et al. Point-of-care ultrasound in pulmonary and pleural infections. "
        "Med Clin (Barc). 2025 [PMID: 40997476]",
        ref_style))

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

if __name__ == "__main__":
    make_doc()
You've run out of free credits. Sign up for a free account to continue using Orris.
This is a shared conversation. Sign in to Orris to start your own chat.