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-exam-notes && ls /home/daytona/workspace/md-exam-notes/

Writing File

~/md-exam-notes/generate_notes.py

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

OUTPUT = "/home/daytona/workspace/md-exam-notes/MD_Medicine_Exam_Notes.pdf"

doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    rightMargin=2*cm,
    leftMargin=2*cm,
    topMargin=2.5*cm,
    bottomMargin=2*cm,
    title="MD Medicine Final Examination Notes",
    author="Orris Medical AI",
)

styles = getSampleStyleSheet()

# Custom styles
TEAL = colors.HexColor("#006D77")
DARK_TEAL = colors.HexColor("#003D4A")
LIGHT_TEAL = colors.HexColor("#E8F4F6")
ORANGE = colors.HexColor("#E76F51")
LIGHT_ORANGE = colors.HexColor("#FFF3EF")
GREY_BG = colors.HexColor("#F5F5F5")
DARK_TEXT = colors.HexColor("#1A1A2E")
RED_BOX = colors.HexColor("#C0392B")
LIGHT_RED = colors.HexColor("#FDEDEC")

cover_title = ParagraphStyle(
    "cover_title", parent=styles["Title"],
    fontSize=26, textColor=DARK_TEAL, spaceAfter=8, alignment=TA_CENTER,
    fontName="Helvetica-Bold"
)
cover_sub = ParagraphStyle(
    "cover_sub", parent=styles["Normal"],
    fontSize=13, textColor=TEAL, spaceAfter=4, alignment=TA_CENTER
)
cover_meta = ParagraphStyle(
    "cover_meta", parent=styles["Normal"],
    fontSize=10, textColor=colors.grey, spaceAfter=2, alignment=TA_CENTER
)
h1 = ParagraphStyle(
    "h1", parent=styles["Heading1"],
    fontSize=16, textColor=colors.white, spaceAfter=2, spaceBefore=14,
    fontName="Helvetica-Bold", backColor=DARK_TEAL,
    leftIndent=-10, rightIndent=-10,
    borderPadding=(6, 10, 6, 10),
)
h2 = ParagraphStyle(
    "h2", parent=styles["Heading2"],
    fontSize=13, textColor=DARK_TEAL, spaceAfter=3, spaceBefore=10,
    fontName="Helvetica-Bold",
    borderPadding=(0, 0, 2, 0),
)
h3 = ParagraphStyle(
    "h3", parent=styles["Heading3"],
    fontSize=11, textColor=ORANGE, spaceAfter=2, spaceBefore=7,
    fontName="Helvetica-Bold",
)
body = ParagraphStyle(
    "body", parent=styles["Normal"],
    fontSize=10, textColor=DARK_TEXT, leading=15, spaceAfter=4,
    alignment=TA_JUSTIFY, fontName="Helvetica"
)
bullet = ParagraphStyle(
    "bullet", parent=styles["Normal"],
    fontSize=10, textColor=DARK_TEXT, leading=14, spaceAfter=3,
    leftIndent=16, bulletIndent=4, fontName="Helvetica"
)
sub_bullet = ParagraphStyle(
    "sub_bullet", parent=styles["Normal"],
    fontSize=9.5, textColor=DARK_TEXT, leading=13, spaceAfter=2,
    leftIndent=30, bulletIndent=18, fontName="Helvetica"
)
note_style = ParagraphStyle(
    "note", parent=styles["Normal"],
    fontSize=9.5, textColor=colors.HexColor("#5D4037"), leading=13, spaceAfter=2,
    leftIndent=10, rightIndent=10, fontName="Helvetica-Oblique",
    backColor=colors.HexColor("#FFF8E1"), borderPadding=(6, 8, 6, 8),
)
key_box = ParagraphStyle(
    "key_box", parent=styles["Normal"],
    fontSize=9.5, textColor=DARK_TEAL, leading=13, spaceAfter=2,
    leftIndent=10, rightIndent=10, fontName="Helvetica",
    backColor=LIGHT_TEAL, borderPadding=(6, 8, 6, 8),
)
warning_box = ParagraphStyle(
    "warning_box", parent=styles["Normal"],
    fontSize=9.5, textColor=RED_BOX, leading=13, spaceAfter=2,
    leftIndent=10, rightIndent=10, fontName="Helvetica-Bold",
    backColor=LIGHT_RED, borderPadding=(6, 8, 6, 8),
)
source_style = ParagraphStyle(
    "source", parent=styles["Normal"],
    fontSize=8, textColor=colors.grey, leading=11, spaceAfter=1,
    fontName="Helvetica-Oblique", alignment=TA_RIGHT
)
table_header = ParagraphStyle(
    "table_header", parent=styles["Normal"],
    fontSize=9.5, textColor=colors.white, fontName="Helvetica-Bold",
    alignment=TA_CENTER
)
table_cell = ParagraphStyle(
    "table_cell", parent=styles["Normal"],
    fontSize=9, textColor=DARK_TEXT, leading=12, fontName="Helvetica"
)

def B(text): return f"<b>{text}</b>"
def I(text): return f"<i>{text}</i>"
def U(text): return f"<u>{text}</u>"

def hline():
    return HRFlowable(width="100%", thickness=1, color=TEAL, spaceAfter=4, spaceBefore=2)

story = []

# ─── COVER PAGE ───────────────────────────────────────────────────────────────
story.append(Spacer(1, 3*cm))

cover_data = [[Paragraph("MD MEDICINE", cover_title)],
              [Paragraph("FINAL EXAMINATION NOTES", cover_title)],
              [Spacer(1, 0.5*cm)],
              [Paragraph("Topic 1", cover_sub)],
              [Paragraph("Approach to Dyspnea &amp; Lung Abscess", ParagraphStyle(
                  "ct2", parent=cover_sub, fontSize=16, textColor=ORANGE, fontName="Helvetica-Bold"))],
              [Spacer(1, 1*cm)],
              [Paragraph("Sources: Harrison's Principles of Internal Medicine 22E (2025) •", cover_meta)],
              [Paragraph("Goldman-Cecil Medicine • Murray &amp; Nadel's Respiratory Medicine •", cover_meta)],
              [Paragraph("Robbins &amp; Kumar Pathology • Tintinalli's Emergency Medicine •", cover_meta)],
              [Paragraph("Fishman's Pulmonary Diseases", cover_meta)],
              [Spacer(1, 1*cm)],
              [Paragraph("Prepared by Orris Medical AI | May 2026", cover_meta)],
             ]
cov_table = Table([[row[0]] for row in cover_data], colWidths=[17*cm])
cov_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,-1), LIGHT_TEAL),
    ("BOX", (0,0), (-1,-1), 2, TEAL),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 20),
    ("RIGHTPADDING", (0,0), (-1,-1), 20),
]))
story.append(cov_table)
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════════════
# SECTION 1: APPROACH TO DYSPNEA
# ════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("SECTION 1: APPROACH TO A CASE OF DYSPNEA", h1))
story.append(Spacer(1, 0.3*cm))

# Definition
story.append(Paragraph("1.1 Definition", h2))
story.append(hline())
story.append(Paragraph(
    "Dyspnea is the sensation of difficult, labored, or <b>unpleasant</b> breathing. "
    "The term \"unpleasant\" is critical — normal exertional breathlessness during exercise "
    "does <b>not</b> qualify as dyspnea. The physiology remains multifactorial; multiple neural "
    "pathways can be involved in processes that lead to dyspnea.",
    body
))
story.append(Paragraph(I("— Goldman-Cecil Medicine"), source_style))
story.append(Spacer(1, 0.2*cm))

# Pathophysiology
story.append(Paragraph("1.2 Pathophysiology of Dyspnea", h2))
story.append(hline())
story.append(Paragraph(
    "Dyspnea is an integrated sensation reflecting a range of sensory inputs "
    "(from lungs, chest wall, airways, vascular structures, chemoreceptors) and motor outputs "
    "to the ventilatory muscles. It arises via <b>four major physiologic mechanisms</b>:",
    body
))

mech_data = [
    [Paragraph(B("Mechanism"), table_header), Paragraph(B("Pathophysiology"), table_header), Paragraph(B("Examples"), table_header)],
    [Paragraph("1. Abnormal Blood Gases", table_cell),
     Paragraph("Hypoxemia and/or hypercapnia → stimulation of chemoreceptors → activation of respiratory controller. (A-a)PO₂ > 0.3 × age = gas exchanger abnormality.", table_cell),
     Paragraph("Pneumonia, COPD, ILD, PE, Pulmonary edema", table_cell)],
    [Paragraph("2. Receptor Stimulation", table_cell),
     Paragraph("Stimulation of sensory receptors (pulmonary C-fibers, irritant receptors, pressure receptors, flow receptors) in airways, lungs, chest wall, vasculature.", table_cell),
     Paragraph("Pulmonary embolism, Left heart failure, Pleural effusion, Bronchospasm (tightness)", table_cell)],
    [Paragraph("3. Increased Mechanical Load", table_cell),
     Paragraph("Increased airway resistance or decreased lung/chest wall compliance → effort-demand mismatch.", table_cell),
     Paragraph("Asthma, COPD, Kyphoscoliosis, Obesity", table_cell)],
    [Paragraph("4. Neuromuscular Weakness", table_cell),
     Paragraph("Inability to handle even normal mechanical loads; body cannot meet ventilatory demands.", table_cell),
     Paragraph("Guillain-Barré, Myasthenia gravis, Diaphragmatic paralysis, Spinal cord injury", table_cell)],
]
mech_table = Table(mech_data, colWidths=[3.8*cm, 7*cm, 5.4*cm])
mech_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("BACKGROUND", (0,1), (-1,1), LIGHT_TEAL),
    ("BACKGROUND", (0,2), (-1,2), colors.white),
    ("BACKGROUND", (0,3), (-1,3), LIGHT_TEAL),
    ("BACKGROUND", (0,4), (-1,4), colors.white),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(mech_table)
story.append(Paragraph(I("— Murray & Nadel's Textbook of Respiratory Medicine"), source_style))
story.append(Spacer(1, 0.4*cm))

story.append(Paragraph(
    "<b>Key sensation descriptors (clinically useful for diagnosis):</b>",
    body
))
story.append(Paragraph("• <b>Air hunger / \"cannot get enough air\"</b> → Stimulation of respiratory controller (chemoreceptor-driven)", bullet))
story.append(Paragraph("• <b>Tightness</b> → Bronchospasm (irritant receptor activation — asthma)", bullet))
story.append(Paragraph("• <b>Work / effort</b> → Increased mechanical load (COPD, obesity)", bullet))
story.append(Paragraph("• <b>Suffocation</b> → Often cardiac (left heart failure)", bullet))
story.append(Spacer(1, 0.3*cm))

# Clinical Approach
story.append(Paragraph("1.3 Clinical Approach to the Patient with Dyspnea", h2))
story.append(hline())

story.append(Paragraph(B("Step 1: Determine Acuity"), h3))
story.append(Paragraph(
    "First classify dyspnea as <b>acute</b> or <b>chronic</b> — this immediately "
    "directs the urgency and type of initial workup.",
    body
))

acuity_data = [
    [Paragraph(B("ACUTE Dyspnea"), table_header), Paragraph(B("CHRONIC Dyspnea"), table_header)],
    [Paragraph("Onset: Sudden (minutes–hours)\nMust rule out LIFE-THREATENING causes FIRST", table_cell),
     Paragraph("Onset: Gradual (weeks–months)\nSystematic evaluation for underlying cause", table_cell)],
    [Paragraph(
        "• Pulmonary embolism\n• Pulmonary edema (cardiogenic/non-cardiogenic)\n"
        "• Acute airway obstruction (anaphylaxis, foreign body)\n"
        "• Pneumothorax (tension or simple)\n• Pneumonia (severe)\n"
        "• Acute exacerbation of COPD/Asthma\n• Cardiac tamponade\n• ACS with LV failure",
        table_cell),
     Paragraph(
        "• COPD\n• Asthma\n• Interstitial lung disease (ILD)\n"
        "• Heart failure (systolic or diastolic)\n• Cardiomyopathy\n"
        "• Pulmonary hypertension\n• Anemia\n• Deconditioning\n"
        "• GERD (laryngospasm/microaspiration)\n• Hyperventilation syndrome\n"
        "• Neuromuscular disease",
        table_cell)],
]
acuity_table = Table(acuity_data, colWidths=[8.25*cm, 8.25*cm])
acuity_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("BACKGROUND", (0,1), (-1,1), LIGHT_TEAL),
    ("BACKGROUND", (0,2), (0,2), colors.HexColor("#FFF3EF")),
    ("BACKGROUND", (1,2), (1,2), LIGHT_TEAL),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 6),
    ("BOTTOMPADDING", (0,0), (-1,-1), 6),
    ("LEFTPADDING", (0,0), (-1,-1), 8),
    ("RIGHTPADDING", (0,0), (-1,-1), 8),
]))
story.append(acuity_table)
story.append(Spacer(1, 0.4*cm))

story.append(Paragraph(B("Step 2: Focused History"), h3))
for pt in [
    "<b>Onset &amp; progression:</b> Sudden (PE, pneumothorax) vs. gradual (ILD, heart failure)",
    "<b>Precipitating/relieving factors:</b> Positional (orthopnea → HF; platypnea → hepatopulmonary syndrome)",
    "<b>Pleuritic pain:</b> PE, pneumonia, pneumothorax",
    "<b>Associated symptoms:</b> Fever (infection), weight loss (malignancy, TB), hemoptysis (PE, Ca, TB), pedal edema (HF), wheezing (asthma)",
    "<b>Exercise tolerance:</b> MRC dyspnea scale (grades I–V)",
    "<b>Risk factors:</b> Smoking (COPD, lung cancer), DVT history (PE), immunosuppression (PCP, fungal), aspiration risks (lung abscess)",
    "<b>Drug history:</b> Amiodarone/methotrexate (ILD), beta-blockers (bronchospasm), ACE inhibitors (cough mimicking dyspnea)",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph(B("Step 3: Physical Examination"), h3))

phys_data = [
    [Paragraph(B("Finding"), table_header), Paragraph(B("Suggests"), table_header)],
    [Paragraph("Tachypnea + accessory muscle use", table_cell), Paragraph("Severe airflow obstruction, pneumonia, PE, pulmonary edema", table_cell)],
    [Paragraph("Wheezing", table_cell), Paragraph("Asthma, COPD, cardiac asthma (left HF)", table_cell)],
    [Paragraph("Stridor", table_cell), Paragraph("Upper airway obstruction (epiglottitis, foreign body, anaphylaxis)", table_cell)],
    [Paragraph("Dullness on percussion", table_cell), Paragraph("Pleural effusion, lobar consolidation/pneumonia", table_cell)],
    [Paragraph("Hyperresonance", table_cell), Paragraph("Pneumothorax, bullous emphysema", table_cell)],
    [Paragraph("Crackles/Rales", table_cell), Paragraph("Pulmonary edema, ILD, pneumonia", table_cell)],
    [Paragraph("Absent breath sounds", table_cell), Paragraph("Pneumothorax, massive pleural effusion", table_cell)],
    [Paragraph("JVD + peripheral edema + S3", table_cell), Paragraph("Congestive heart failure", table_cell)],
    [Paragraph("Pulsus paradoxus >10 mmHg", table_cell), Paragraph("Severe asthma, cardiac tamponade, COPD exacerbation", table_cell)],
    [Paragraph("Cyanosis", table_cell), Paragraph("Severe hypoxemia (SpO₂ <85%, PaO₂ <50 mmHg)", table_cell)],
    [Paragraph("Kussmaul breathing", table_cell), Paragraph("Metabolic acidosis (DKA, severe lactic acidosis)", table_cell)],
    [Paragraph("Paradoxical abdominal motion", table_cell), Paragraph("Diaphragm paralysis", table_cell)],
]
phys_table = Table(phys_data, colWidths=[6*cm, 10.5*cm])
phys_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
    ("TOPPADDING", (0,0), (-1,-1), 4),
    ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(phys_table)
story.append(Paragraph(I("— Murray & Nadel's Textbook of Respiratory Medicine (Table 36.2)"), source_style))
story.append(Spacer(1, 0.4*cm))

story.append(Paragraph(B("Step 4: Investigations"), h3))
story.append(Paragraph(
    "<b>Basic (all patients):</b>",
    body
))
for pt in [
    "<b>Chest X-ray (CXR):</b> First-line — identifies consolidation, pleural effusion, pneumothorax, cardiomegaly, hyperinflation",
    "<b>ECG:</b> Rules out ACS, arrhythmia, right heart strain (S1Q3T3 pattern in PE)",
    "<b>Pulse oximetry / ABG:</b> Quantifies hypoxemia and acid-base status. Calculate A-a gradient",
    "<b>CBC:</b> Anaemia, leukocytosis (infection), eosinophilia (allergic)",
    "<b>BNP/NT-proBNP:</b> Extremely useful in acute dyspnea — distinguishes cardiac (↑BNP) from pulmonary causes",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("<b>Targeted (based on clinical suspicion):</b>", body))
for pt in [
    "<b>D-dimer + CT pulmonary angiography (CTPA):</b> If PE suspected (Wells score)",
    "<b>Spirometry/PFTs:</b> Obstructive (FEV₁/FVC <0.7 — asthma, COPD) vs. Restrictive (↓TLC — ILD, pleural disease)",
    "<b>CT chest:</b> For ILD pattern, cavitary lesions, mediastinal mass",
    "<b>Echocardiography:</b> LV/RV function, pericardial effusion, valvular disease",
    "<b>Point-of-care ultrasound (POCUS):</b> Rapidly identifies pleural effusion, B-lines (pulmonary edema), absent lung sliding (pneumothorax), cardiac tamponade",
    "<b>Exercise stress test with oximetry:</b> Unexplained exertional dyspnea",
    "<b>Sputum culture / BAL:</b> Suspected infection",
]:
    story.append(Paragraph(f"• {pt}", bullet))

story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(
    "⚠️  <b>Red Flags in Dyspnea requiring urgent evaluation:</b> Hemoptysis • Prominent dyspnea at rest or at night • "
    "Hoarseness • Systemic symptoms • Fever • Smoker >45 years with new/changed cough • "
    "Adults 55–80 with ≥30 pack-year smoking history",
    warning_box
))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph(B("Step 5: Management"), h3))
story.append(Paragraph(
    "Initial management targets the specific etiology identified. Universal initial steps:",
    body
))
for pt in [
    "Maintain airway — position, airway adjuncts if needed",
    "Supplemental oxygen — titrate to SpO₂ ≥94% (88–92% in COPD to avoid hypercapnic drive suppression)",
    "IV access + monitoring (SpO₂, continuous ECG)",
    "Treat life-threatening cause immediately (e.g., needle decompression for tension pneumothorax, bronchodilators for asthma, diuretics for pulmonary edema, anticoagulation for PE)",
    "Anxiolytics/opioids (low-dose morphine) for symptomatic relief in refractory dyspnea (palliative/end-stage)",
]:
    story.append(Paragraph(f"• {pt}", bullet))

story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════════════
# SECTION 2: LUNG ABSCESS
# ════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("SECTION 2: LUNG ABSCESS", h1))
story.append(Spacer(1, 0.3*cm))

# Definition
story.append(Paragraph("2.1 Definition and Classification", h2))
story.append(hline())
story.append(Paragraph(
    "Lung abscess represents <b>necrosis and cavitation of the lung parenchyma</b> following microbial infection. "
    "It usually manifests as a single dominant cavity <b>&gt;2 cm in diameter</b>. "
    "The abscess results from localized suppuration within the pulmonary parenchyma.",
    body
))

story.append(Spacer(1, 0.2*cm))
class_data = [
    [Paragraph(B("By Aetiology"), table_header), Paragraph(B("By Duration"), table_header)],
    [Paragraph(
        "<b>Primary (~80%):</b>\n"
        "• Aspiration (anaerobic bacteria)\n"
        "• Occurs in otherwise normal hosts\n"
        "• Anaerobes + microaerophilic streptococci\n"
        "• Classic: post-aspiration event",
        table_cell),
     Paragraph(
        "<b>Acute:</b> &lt;4–6 weeks duration\n\n"
        "<b>Chronic:</b> &gt;4–6 weeks duration\n"
        "(~40% of cases)\n"
        "Associated with higher morbidity",
        table_cell)],
    [Paragraph(
        "<b>Secondary (~20%):</b>\n"
        "• Underlying obstruction (tumor, foreign body)\n"
        "• Immunocompromise (HIV, transplant)\n"
        "• Hematogenous spread (endocarditis)\n"
        "• Mortality up to 75% in some series",
        table_cell),
     Paragraph(
        "<b>Putrid abscess:</b>\n"
        "Foul-smelling sputum — indicates\n"
        "anaerobic organisms\n\n"
        "<b>Non-putrid:</b> aerobic bacteria\n"
        "(S. aureus, Gram-negatives)",
        table_cell)],
]
class_table = Table(class_data, colWidths=[8.25*cm, 8.25*cm])
class_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("BACKGROUND", (0,1), (-1,1), LIGHT_ORANGE),
    ("BACKGROUND", (0,2), (-1,2), LIGHT_TEAL),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 6),
    ("BOTTOMPADDING", (0,0), (-1,-1), 6),
    ("LEFTPADDING", (0,0), (-1,-1), 8),
    ("RIGHTPADDING", (0,0), (-1,-1), 8),
]))
story.append(class_table)
story.append(Paragraph(I("— Harrison's Principles of Internal Medicine 22E (2025)"), source_style))
story.append(Spacer(1, 0.4*cm))

# Epidemiology & Risk Factors
story.append(Paragraph("2.2 Epidemiology and Risk Factors", h2))
story.append(hline())
story.append(Paragraph("<b>Demographics:</b> Middle-aged men > women", body))
story.append(Paragraph("<b>Key risk factors for primary lung abscess (aspiration-related):</b>", body))
for rf in [
    "Altered mental status (alcoholism, drug overdose, seizures, general anaesthesia)",
    "Bulbar dysfunction, prior CVA/cerebrovascular disease, neuromuscular disease",
    "Esophageal dysmotility / strictures / tumors / GERD",
    "Prolonged recumbent position (hospitalized/bedridden patients)",
    "<b>Periodontal disease and gingivitis</b> — oral anaerobic colonization is a prerequisite; lung abscess is <b>rare in edentulous patients</b>",
    "Gastric distension",
]:
    story.append(Paragraph(f"• {rf}", bullet))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(
    "💡 <b>High-yield exam point:</b> The finding of lung abscess in an <i>edentulous patient</i> should raise suspicion "
    "for an obstructing lesion (malignancy), pulmonary embolus, septic embolus, or an unusual pathogen. "
    "Dental hygiene is directly protective.",
    key_box
))
story.append(Spacer(1, 0.3*cm))

# Pathophysiology
story.append(Paragraph("2.3 Pathophysiology", h2))
story.append(hline())
story.append(Paragraph(
    "The causative organism is introduced into the lung by one or more of the following mechanisms:",
    body
))

path_data = [
    [Paragraph(B("Mechanism"), table_header), Paragraph(B("Details"), table_header), Paragraph(B("Common Pathogens"), table_header)],
    [Paragraph("1. Aspiration\n(most common)", table_cell),
     Paragraph("Aspiration of infected oropharyngeal contents (carious teeth, infected sinuses) during: oral surgery, anaesthesia, coma, alcoholic intoxication, seizures, impaired gag reflex. Gastric contents + oropharyngeal flora during reflux/regurgitation.", table_cell),
     Paragraph("Anaerobes: Prevotella, Fusobacterium, Bacteroides, Peptostreptococcus spp.\nMicroaerophilic streptococci", table_cell)],
    [Paragraph("2. Post-pneumonia\nNecrotization", table_cell),
     Paragraph("Complication of necrotizing bacterial pneumonia where alveolar consolidation progresses to liquefactive necrosis.", table_cell),
     Paragraph("S. aureus, S. pyogenes, K. pneumoniae, Pseudomonas spp., Type 3 Pneumococcus", table_cell)],
    [Paragraph("3. Bronchial Obstruction", table_cell),
     Paragraph("Tumor or foreign body → impaired drainage → distal atelectasis + aspiration of secretions → abscess formation. An abscess may also form within a necrotic tumor.", table_cell),
     Paragraph("Mixed flora; may develop within carcinoma (squamous cell most common)", table_cell)],
    [Paragraph("4. Hematogenous / Septic Emboli", table_cell),
     Paragraph("Bacteremia → septic emboli lodge in pulmonary vasculature → multiple bilateral peripheral abscesses. Classic: right-sided endocarditis, Lemierre's syndrome (IJV thrombophlebitis).", table_cell),
     Paragraph("S. aureus (endocarditis), Fusobacterium necrophorum (Lemierre's)", table_cell)],
    [Paragraph("5. Direct Extension / Trauma", table_cell),
     Paragraph("Penetrating chest trauma; subphrenic abscess (amoebiasis extends to right lower lobe via diaphragm).", table_cell),
     Paragraph("Entamoeba histolytica (right lower lobe), Mixed flora", table_cell)],
]
path_table = Table(path_data, colWidths=[3*cm, 8*cm, 5.5*cm])
path_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_ORANGE, LIGHT_TEAL]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(path_table)
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("<b>Sequence of pathological events (Robbins Pathology):</b>", body))
for step in [
    "Microorganisms access the alveoli → acute inflammatory exudate (pneumonia phase)",
    "Progressive tissue necrosis → suppuration within parenchyma (1–2 weeks for cavity formation)",
    "Abscess enlarges → ruptures into airways → partial drainage → <b>air-fluid level on CXR</b>",
    "Cavity may become lined with regenerated epithelium (chronic phase)",
    "Complications: rupture into pleural space (empyema, bronchopleural fistula), septic emboli (brain abscess), massive haemoptysis",
]:
    story.append(Paragraph(f"• {step}", bullet))

story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("<b>Anatomical location of abscesses (clinically important):</b>", body))
for pt in [
    "<b>Aspiration abscesses:</b> Right > Left (more vertical right main bronchus). Right-sided: <b>posterior segment of RUL</b> and <b>apical segment of RLL</b> (gravity-dependent — supine recumbent position). Left-sided: posterior segment LUL, apical segment LLL",
    "<b>Post-pneumonia:</b> Multiple, basal, scattered",
    "<b>Hematogenous:</b> Multiple, bilateral, peripheral (any region)",
    "<b>Amoebiasis:</b> Almost always <b>right lower lobe</b> (direct extension from liver abscess through diaphragm)",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Paragraph(I("— Robbins & Kumar Basic Pathology; Fishman's Pulmonary Diseases; Harrison's 22E"), source_style))
story.append(Spacer(1, 0.3*cm))

# Microbiology
story.append(Paragraph("2.4 Microbiology", h2))
story.append(hline())
story.append(Paragraph(
    "Anaerobes are present in <b>almost all lung abscesses</b> and are the <b>exclusive isolates in 33–67%</b> of cases "
    "(Bartlett & Finegold: 46% only anaerobes, 43% mixed flora). The most common organisms reflect oral commensals:",
    body
))

micro_data = [
    [Paragraph(B("Clinical Scenario"), table_header), Paragraph(B("Key Pathogens"), table_header)],
    [Paragraph("Primary abscess (aspiration)", table_cell),
     Paragraph("Prevotella spp., Fusobacterium spp., Bacteroides spp., Peptostreptococcus spp., microaerophilic streptococci (Streptococcus milleri group)", table_cell)],
    [Paragraph("Secondary abscess (immunocompromise)", table_cell),
     Paragraph("S. aureus (MRSA), P. aeruginosa, Enterobacteriaceae (Klebsiella — classic 'bulging fissure'), Nocardia spp., Aspergillus spp., Mucorales, Cryptococcus spp., PCP (Pneumocystis jirovecii)", table_cell)],
    [Paragraph("Septic emboli", table_cell),
     Paragraph("S. aureus (right-sided endocarditis), Fusobacterium necrophorum (Lemierre's syndrome)", table_cell)],
    [Paragraph("Endemic infections", table_cell),
     Paragraph("M. tuberculosis, M. avium, M. kansasii, Coccidioides, Histoplasma, Blastomyces (important cavitary mimics)", table_cell)],
    [Paragraph("Parasitic", table_cell),
     Paragraph("Entamoeba histolytica (right lower lobe), Paragonimus westermani, Echinococcus granulosus (hydatid cyst — must NOT drain blindly)", table_cell)],
    [Paragraph("Nosocomial / Post-operative", table_cell),
     Paragraph("Gram-negatives (K. pneumoniae — classic 'currant jelly' sputum, P. aeruginosa), S. aureus — hospitalacquired antibiotic-resistance patterns", table_cell)],
]
micro_table = Table(micro_data, colWidths=[4.5*cm, 12*cm])
micro_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(micro_table)
story.append(Paragraph(I("— Harrison's 22E (Table 132-1); Fishman's Pulmonary Diseases; Robbins Pathology"), source_style))
story.append(Spacer(1, 0.4*cm))

# Clinical Features
story.append(Paragraph("2.5 Clinical Features", h2))
story.append(hline())
story.append(Paragraph(
    "Lung abscess typically has an <b>indolent presentation</b> — patients present after <b>2–4 weeks</b> of symptoms. "
    "This distinguishes it from acute pneumonia. "
    "Because development is slow, classic features of sepsis (fever, tachycardia, tachypnea) may initially be absent or subtle.",
    body
))
story.append(Spacer(1, 0.15*cm))

sympt_data = [
    [Paragraph(B("Symptom"), table_header), Paragraph(B("Characteristics / High-yield Points"), table_header)],
    [Paragraph("Cough", table_cell), Paragraph("May be dry initially; becomes productive after abscess communicates with bronchus. Classically produces large amounts of purulent, foul-smelling sputum ('putrid' = anaerobic; non-putrid = aerobic).", table_cell)],
    [Paragraph("Fever", table_cell), Paragraph("Present but may be low-grade; remittent pattern common. Often absent early in course.", table_cell)],
    [Paragraph("Pleuritic chest pain", table_cell), Paragraph("When abscess involves the pleural surface; also seen if empyema develops.", table_cell)],
    [Paragraph("Haemoptysis", table_cell), Paragraph("Occurs; can be life-threatening (massive haemoptysis) as a late complication.", table_cell)],
    [Paragraph("Constitutional symptoms", table_cell), Paragraph("Weight loss, night sweats, malaise — prominent in chronic lung abscess (can mimic tuberculosis).", table_cell)],
    [Paragraph("Digital clubbing", table_cell), Paragraph("Seen in chronic lung abscess (weeks–months); also with bronchiectasis and empyema.", table_cell)],
    [Paragraph("Anaemia", table_cell), Paragraph("Normocytic, normochromic; typical of chronic infection/inflammation.", table_cell)],
]
sympt_table = Table(sympt_data, colWidths=[4*cm, 12.5*cm])
sympt_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(sympt_table)
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("<b>Physical examination findings:</b>", body))
for pt in [
    "Dullness to percussion + bronchial breathing over consolidation",
    "Amphoric breath sounds (hollow, bottle-like quality) — pathognomonic of cavitary lesion communicating with bronchus",
    "Coarse crepitations / rhonchi",
    "Evidence of poor dental hygiene/periodontal disease (in primary abscess)",
    "Signs of complications: pleural rub (pleuritis), signs of empyema (stony dull, absent breath sounds), neurological signs (brain abscess from septic emboli)",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Spacer(1, 0.3*cm))

# Diagnosis
story.append(Paragraph("2.6 Investigations and Diagnosis", h2))
story.append(hline())

story.append(Paragraph(B("Blood Investigations:"), body))
for pt in [
    "CBC: Leukocytosis (polymorphonuclear predominance), anaemia in chronic cases",
    "ESR / CRP: Raised (nonspecific markers of inflammation)",
    "LFTs, renal function: Baseline and to monitor drug toxicity",
    "Blood cultures: Especially in secondary abscess / immunocompromised; positive in bacteraemic cases",
    "HIV serology: If secondary abscess or unusual pathogen",
]:
    story.append(Paragraph(f"• {pt}", bullet))

story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(B("Sputum Investigations:"), body))
for pt in [
    "<b>Gram stain + culture:</b> Aerobes and anaerobes; interpret with caution (oral contamination)",
    "<b>AFB smear + culture:</b> Rule out tuberculosis (critical in endemic areas)",
    "<b>Fungal stains/culture:</b> If immunocompromised or atypical presentation",
    "<b>Cytology:</b> If malignancy suspected (cavity within a tumor)",
]:
    story.append(Paragraph(f"• {pt}", bullet))

story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(B("Imaging (KEY):"), body))

img_data = [
    [Paragraph(B("Modality"), table_header), Paragraph(B("Findings"), table_header)],
    [Paragraph("Chest X-ray\n(CXR)", table_cell),
     Paragraph(
        "• Dense consolidation with or without cavity\n"
        "• <b>Air-fluid level</b> inside a cavitary lesion = classic sign (indicates communication with airway)\n"
        "• Location: posterior segment RUL / apical segment RLL (aspiration-related)\n"
        "• Thick-walled cavity with shaggy inner lining (vs. thin-walled = bulla/cyst)",
        table_cell)],
    [Paragraph("CT Chest\n(preferred)", table_cell),
     Paragraph(
        "• Superior sensitivity for cavity detection, even without airway communication\n"
        "• Defines cavity wall thickness, internal structure, surrounding parenchyma\n"
        "• Identifies associated complications (pleural involvement, lymphadenopathy, obstruction)\n"
        "• Differentiates empyema from lung abscess (see below)\n"
        "• Guides percutaneous drainage",
        table_cell)],
    [Paragraph("Ultrasound\n(thoracic)", table_cell),
     Paragraph(
        "• Identifies pleural involvement, guides drainage\n"
        "• Cannot assess lung parenchyma well (air-containing lung blocks US)",
        table_cell)],
    [Paragraph("Bronchoscopy\n(flexible)", table_cell),
     Paragraph(
        "• Rules out endobronchial obstruction (tumor, foreign body)\n"
        "• BAL for culture (especially anaerobes, TB, fungi)\n"
        "• Transbronchial drainage of abscess (risk: contralateral spillage)\n"
        "• Mandatory if no response to antibiotics in 2 weeks",
        table_cell)],
]
img_table = Table(img_data, colWidths=[3*cm, 13.5*cm])
img_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(img_table)
story.append(Spacer(1, 0.2*cm))

# DDx table
story.append(Paragraph(B("Differentiating Lung Abscess from Empyema (CT criteria):"), body))
ddx_data = [
    [Paragraph(B("Feature"), table_header), Paragraph(B("Lung Abscess"), table_header), Paragraph(B("Empyema"), table_header)],
    [Paragraph("Shape", table_cell), Paragraph("Round / spherical (cross-sections equal in two planes)", table_cell), Paragraph("Lenticular / crescentic (confirms within pleural space)", table_cell)],
    [Paragraph("Wall", table_cell), Paragraph("Thick, irregular, shaggy inner wall", table_cell), Paragraph("Thin, smooth wall; 'split pleura sign'", table_cell)],
    [Paragraph("Lung compression", table_cell), Paragraph("Lung tissue surrounding the cavity", table_cell), Paragraph("Compresses adjacent lung", table_cell)],
    [Paragraph("Air-fluid level", table_cell), Paragraph("Present if communication with airway", table_cell), Paragraph("Present if bronchopleural fistula", table_cell)],
    [Paragraph("Vessels/bronchi", table_cell), Paragraph("Course around the cavity", table_cell), Paragraph("Displaced from pleura", table_cell)],
]
ddx_table = Table(ddx_data, colWidths=[3.5*cm, 6.5*cm, 6.5*cm])
ddx_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_ORANGE, LIGHT_TEAL]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 4),
    ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(ddx_table)
story.append(Spacer(1, 0.3*cm))

# Differential Diagnosis
story.append(Paragraph("2.7 Differential Diagnosis — Cavitary Lung Lesions", h2))
story.append(hline())
story.append(Paragraph(
    "The mnemonic <b>CAVITY</b> is useful for remembering the DDx of pulmonary cavities "
    "(a common exam question paired with lung abscess):",
    body
))
story.append(Spacer(1, 0.1*cm))

ddx2_data = [
    [Paragraph(B("Category"), table_header), Paragraph(B("Specific Diagnosis"), table_header), Paragraph(B("Differentiating Features"), table_header)],
    [Paragraph("Infectious — Bacterial", table_cell),
     Paragraph("Lung abscess (anaerobic/aerobic), Infected bullae, Tuberculosis, Actinomycosis, Nocardiosis", table_cell),
     Paragraph("Clinical context, sputum AFB, culture", table_cell)],
    [Paragraph("Infectious — Fungal", table_cell),
     Paragraph("Aspergillosis (aspergilloma — 'fungus ball'), Coccidioidomycosis, Histoplasmosis, Blastomycosis, Mucormycosis, Cryptococcus", table_cell),
     Paragraph("Immunocompromised host; serology, BAL fungal culture; 'air crescent sign' (aspergilloma)", table_cell)],
    [Paragraph("Infectious — Parasitic", table_cell),
     Paragraph("Echinococcus (hydatid cyst), Entamoeba histolytica, Paragonimus westermani", table_cell),
     Paragraph("Travel history; serology; DO NOT percutaneously drain hydatid cyst (anaphylaxis risk)", table_cell)],
    [Paragraph("Neoplastic", table_cell),
     Paragraph("Squamous cell carcinoma (most common to cavitate), Adenocarcinoma, Metastases (colorectal, renal cell), Lymphoma", table_cell),
     Paragraph("Thick irregular wall, no air-fluid level; cytology; biopsy; no/minimal fever", table_cell)],
    [Paragraph("Inflammatory / Vasculitic", table_cell),
     Paragraph("Granulomatosis with polyangiitis (GPA, formerly Wegener's), Rheumatoid nodules, Sarcoidosis", table_cell),
     Paragraph("Systemic vasculitis features, cANCA, bilateral nodules; no infective signs", table_cell)],
    [Paragraph("Other", table_cell),
     Paragraph("Foreign body aspiration, Pulmonary infarction (post-PE), Pulmonary sequestration, Bullae (infected)", table_cell),
     Paragraph("Clinical context, CT angiography, bronchoscopy", table_cell)],
]
ddx2_table = Table(ddx2_data, colWidths=[3.5*cm, 7*cm, 6*cm])
ddx2_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(ddx2_table)
story.append(Paragraph(I("— Tintinalli's Emergency Medicine (Table 66-2); Fishman's Pulmonary Diseases"), source_style))
story.append(Spacer(1, 0.3*cm))

# Management
story.append(Paragraph("2.8 Management", h2))
story.append(hline())

story.append(Paragraph(B("Principles of Treatment:"), body))
for pt in [
    "Antibiotics are the <b>primary treatment</b> for lung abscess (established since 1940s–50s)",
    "Surgery was the mainstay pre-antibiotic era; now reserved for failures",
    "Treat until imaging shows <b>clearance or regression to a small scar</b>",
    "Adequate drainage (postural physiotherapy, positional drainage) is adjunctive",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(B("Antibiotic Therapy (Primary Lung Abscess):"), h3))
story.append(Paragraph(
    "Clindamycin is the drug of choice based on clinical trials showing superiority over penicillin. "
    "Oral anaerobes commonly produce β-lactamases, making penicillin alone inadequate.",
    body
))

abx_data = [
    [Paragraph(B("Regimen"), table_header), Paragraph(B("Dosing"), table_header), Paragraph(B("Notes"), table_header)],
    [Paragraph("1. Clindamycin\n(FIRST-LINE)", table_cell),
     Paragraph("600 mg IV TDS → (on clinical improvement) 300 mg PO QDS", table_cell),
     Paragraph("Switch to oral when afebrile + clinically improving. Covers anaerobes + microaerophilic streptococci. Risk: C. difficile colitis.", table_cell)],
    [Paragraph("2. Amoxicillin-clavulanate\n(β-lactam/β-lactamase inhibitor)", table_cell),
     Paragraph("IV ampicillin-sulbactam 3g q6h → oral amoxicillin-clavulanate (co-amoxiclav)", table_cell),
     Paragraph("Alternative first-line. Covers β-lactamase-producing anaerobes. Stepdown to oral once stable.", table_cell)],
    [Paragraph("3. Moxifloxacin", table_cell),
     Paragraph("400 mg PO once daily", table_cell),
     Paragraph("Small trial showed equivalence to ampicillin-sulbactam. Useful for oral step-down in penicillin allergy.", table_cell)],
    [Paragraph("4. Carbapenem\n(imipenem / meropenem)", table_cell),
     Paragraph("Imipenem 500 mg IV q6h or meropenem 1g IV q8h", table_cell),
     Paragraph("Reserved for severe/refractory cases, nosocomial abscesses, or resistant organisms (Pseudomonas, ESBL).", table_cell)],
    [Paragraph("⚠️ Metronidazole\n(ALONE — NOT adequate)", table_cell),
     Paragraph("—", table_cell),
     Paragraph("Covers anaerobes but NOT microaerophilic streptococci. Clinical failures reported when used as monotherapy.", table_cell)],
]
abx_table = Table(abx_data, colWidths=[3.5*cm, 5.5*cm, 7.5*cm])
abx_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("BACKGROUND", (0,1), (-1,1), colors.HexColor("#E8F5E9")),
    ("ROWBACKGROUNDS", (0,2), (-1,3), [LIGHT_TEAL, colors.white]),
    ("BACKGROUND", (0,4), (-1,4), LIGHT_ORANGE),
    ("BACKGROUND", (0,5), (-1,5), LIGHT_RED),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(abx_table)
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(
    "📌 <b>Duration of treatment:</b> Continue until imaging shows clearance or small residual scar. "
    "Typically <b>3–4 weeks minimum</b>; often <b>6–14 weeks</b>. "
    "Literature suggests ≥6 weeks may be associated with better outcomes. "
    "For chronic or secondary abscesses, even longer courses are required.",
    key_box
))
story.append(Spacer(1, 0.25*cm))

story.append(Paragraph(B("Antibiotic Therapy (Secondary Lung Abscess):"), h3))
story.append(Paragraph(
    "Cover the identified pathogen. Regimen and duration vary widely based on host immune state and causative organism. "
    "Address the underlying predisposing condition (relieve obstruction, treat immunocompromise).",
    body
))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(B("Drainage Procedures:"), h3))
for pt in [
    "<b>Spontaneous bronchial drainage:</b> Occurs in most patients via communication of the abscess with the tracheobronchial tree — signalled by appearance of an air-fluid level on CXR. Postural drainage and chest physiotherapy aid this process.",
    "<b>Percutaneous drainage (CT/US-guided):</b> Success rate ~84%; complication rate ~16%. Indicated when: abscess &gt;6–8 cm, failure of antibiotic therapy, patient is poor surgical candidate. Complications: pleural space contamination, pneumothorax, haemothorax.",
    "<b>Transbronchial drainage:</b> Risk of contralateral lung contamination; generally reserved for specific indications.",
    "<b>Open surgical drainage:</b> Historical; reserved for large complicated abscesses unresponsive to all other measures.",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(B("Surgical Resection:"), h3))
for pt in [
    "Indicated for persistent infection unresponsive to antibiotics + drainage",
    "Large abscesses (&gt;6–8 cm) less likely to respond to medical therapy",
    "Approximately 11–21% of lung abscesses require surgical or percutaneous drainage",
    "Goal: balance procedural morbidity/mortality against need for definitive clearance",
    "Procedures: lobectomy (most common), pneumonectomy (last resort), cavernoscopy",
]:
    story.append(Paragraph(f"• {pt}", bullet))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(
    "⚠️  <b>Reasons for failure of medical treatment (exam-favourite list):</b>\n"
    "Bronchial obstruction (neoplasm, foreign body) • Nonbacterial cause (neoplasm, fungi, vasculitis, sequestration) • "
    "Large cavity size (&gt;6 cm diameter) • Empyema • Mycobacteria • Wrong antibiotic / resistant organism",
    warning_box
))
story.append(Spacer(1, 0.3*cm))

# Complications
story.append(Paragraph("2.9 Complications", h2))
story.append(hline())
for comp, detail in [
    ("Empyema thoracis", "Rupture of abscess into pleural space — may result in bronchopleural fistula"),
    ("Pneumothorax / Tension pneumothorax", "Rupture of abscess or bronchopleural fistula"),
    ("Life-threatening haemoptysis", "Erosion of a pulmonary artery branch — surgical emergency"),
    ("Brain abscess / Meningitis", "Septic embolisation of abscess contents via pulmonary veins to CNS"),
    ("Bronchiectasis", "Secondary to local airway damage from prolonged infection"),
    ("Pneumatocele (persistent cystic change)", "Especially with large cavities; more common in children with Staphylococcal pneumonia"),
    ("Massive aspiration of abscess contents", "If abscess suddenly drains — contaminates other lung segments"),
    ("Septicaemia / Distant abscesses", "Haematogenous spread — liver abscess, psoas abscess"),
]:
    story.append(Paragraph(f"• <b>{comp}:</b> {detail}", bullet))
story.append(Spacer(1, 0.3*cm))

# Prognosis
story.append(Paragraph("2.10 Prognosis and Prevention", h2))
story.append(hline())

prog_data = [
    [Paragraph(B("Factor"), table_header), Paragraph(B("Primary Abscess"), table_header), Paragraph(B("Secondary Abscess"), table_header)],
    [Paragraph("Mortality rate", table_cell),
     Paragraph("As low as 2% with appropriate management", table_cell),
     Paragraph("As high as 50–75% in some series", table_cell)],
    [Paragraph("Poor prognostic factors", table_cell),
     Paragraph("Age &gt;60, aerobic bacteria, sepsis at presentation, duration &gt;8 weeks, cavity size &gt;6 cm", table_cell),
     Paragraph("Malignancy-associated, immunosuppression, aerobic bacteria", table_cell)],
    [Paragraph("Response to antibiotics", table_cell),
     Paragraph("10–20% do NOT respond; up to 7 days may be needed to defervesce even with correct therapy", table_cell),
     Paragraph("Poorer response; additional interventions often required", table_cell)],
]
prog_table = Table(prog_data, colWidths=[3.5*cm, 6.5*cm, 6.5*cm])
prog_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(prog_table)
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("<b>Prevention strategies:</b>", body))
for prev in [
    "Meticulous oral hygiene and regular dental care (reduces oral anaerobic colonization)",
    "Airway protection during procedures — cuffed endotracheal tube for oral surgery and general anaesthesia",
    "Aspiration precautions in high-risk patients (HOB elevation 30–45°, minimise sedation, PPI for GERD)",
    "Prompt treatment of aspiration pneumonia to prevent progression to abscess",
    "Treatment of underlying predisposing conditions",
]:
    story.append(Paragraph(f"• {prev}", bullet))
story.append(Paragraph(I("— Harrison's Principles of Internal Medicine 22E (2025)"), source_style))
story.append(Spacer(1, 0.3*cm))

# Quick Summary / Mnemonics
story.append(PageBreak())
story.append(Paragraph("SECTION 3: HIGH-YIELD SUMMARY &amp; EXAM MNEMONICS", h1))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("3.1 Quick Summary — Lung Abscess at a Glance", h2))
story.append(hline())

summary_data = [
    [Paragraph(B("Feature"), table_header), Paragraph(B("Key Facts"), table_header)],
    [Paragraph("Definition", table_cell), Paragraph("Necrosis + cavitation of lung parenchyma &gt;2 cm from microbial infection", table_cell)],
    [Paragraph("Commonest cause", table_cell), Paragraph("Aspiration of oropharyngeal anaerobes (primary, ~80%)", table_cell)],
    [Paragraph("Classic organism", table_cell), Paragraph("Prevotella, Fusobacterium, Bacteroides, Peptostreptococcus (oral anaerobes)", table_cell)],
    [Paragraph("Classic location", table_cell), Paragraph("Posterior segment RUL + apical segment RLL (gravity-dependent aspiration)", table_cell)],
    [Paragraph("Classic CXR", table_cell), Paragraph("Air-fluid level in a thick-walled cavity (right side > left)", table_cell)],
    [Paragraph("Presentation", table_cell), Paragraph("2–4 weeks of cough (purulent foul sputum), fever, weight loss, night sweats", table_cell)],
    [Paragraph("First-line treatment", table_cell), Paragraph("Clindamycin IV → PO OR IV amoxicillin-clavulanate → oral", table_cell)],
    [Paragraph("NOT use alone", table_cell), Paragraph("Metronidazole (misses microaerophilic streptococci)", table_cell)],
    [Paragraph("Treatment duration", table_cell), Paragraph("Minimum 3–4 weeks; until imaging clears (up to 14 weeks)", table_cell)],
    [Paragraph("Surgical indication", table_cell), Paragraph("Failure of antibiotics; cavity &gt;6–8 cm; underlying obstruction", table_cell)],
    [Paragraph("Key prognostic factor", table_cell), Paragraph("Primary: mortality ~2%; Secondary: up to 75%. Cavity &gt;6 cm = poor prognosis.", table_cell)],
]
summary_table = Table(summary_data, colWidths=[4*cm, 12.5*cm])
summary_table.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), DARK_TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_TEAL, colors.white]),
    ("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#B0BEC5")),
    ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING", (0,0), (-1,-1), 6),
]))
story.append(summary_table)
story.append(Spacer(1, 0.4*cm))

story.append(Paragraph("3.2 Mnemonics for MD Examinations", h2))
story.append(hline())

story.append(Paragraph(B("Predisposing factors for Lung Abscess — \"ABCDE ASPIRATION\":"), body))
for item in [
    "A — Alcoholism / Altered consciousness / Anaesthesia",
    "B — Bulbar palsy / Bulbar dysfunction",
    "C — CVA (cerebrovascular accident)",
    "D — Dental disease (periodontal disease)",
    "E — Epilepsy (seizures) / Esophageal disease",
    "+ Aspiration of foreign body, malignancy, immunosuppression",
]:
    story.append(Paragraph(f"    • {item}", bullet))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(B("Causes of Cavitary Lung Lesion — Mnemonic \"CAVITY\":"), body))
for item in [
    "C — Cancer (squamous cell, metastasis)",
    "A — Abscess (bacterial: anaerobic, aerobic; fungal)",
    "V — Vasculitis (GPA — Wegener's granulomatosis)",
    "I — Infection — special: TB, fungi, parasites",
    "T — Trauma / Infarction (post-embolic cavitation)",
    "Y — Your diagnosis must include: foreign body, sequestration, infected bulla/cyst",
]:
    story.append(Paragraph(f"    • {item}", bullet))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph(B("Approach to Dyspnea — \"ABCDE of Assessment\":"), body))
for item in [
    "A — Acuity (Acute vs. Chronic)",
    "B — Breathlessness quality (air hunger / tightness / effort)",
    "C — Cause (cardiac vs. pulmonary vs. metabolic vs. neuromuscular)",
    "D — Diagnosis (History + PEx + Investigations: CXR, ECG, ABG, BNP, CTPA, PFTs)",
    "E — Emergency treatment (O₂, position, treat cause; don't delay in acute setting)",
]:
    story.append(Paragraph(f"    • {item}", bullet))
story.append(Spacer(1, 0.3*cm))

# Sources
story.append(Paragraph("3.3 References / Sources", h2))
story.append(hline())
refs = [
    "Harrison's Principles of Internal Medicine, 22nd Edition (2025) — Chapter 132: Lung Abscess",
    "Goldman-Cecil Medicine, International Edition — Chapter 71: Approach to the Patient with Dyspnea",
    "Murray & Nadel's Textbook of Respiratory Medicine (2-Volume) — Chapter 36: Diagnostic Approach to Dyspnea",
    "Robbins & Kumar Basic Pathology (Robbins Pathology) — Chapter: Lung Abscess",
    "Tintinalli's Emergency Medicine: A Comprehensive Study — Chapter 66: Lung Abscess",
    "Fishman's Pulmonary Diseases and Disorders (2-Volume Set) — Chapter 127: Lung Abscess",
    "Sabiston Textbook of Surgery: The Biological Basis of Modern Surgical Practice — Chapter: Lung Abscess",
]
for i, ref in enumerate(refs, 1):
    story.append(Paragraph(f"{i}. {ref}", ParagraphStyle("ref_num", parent=body, fontSize=9.5, leading=13)))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph(
    "This document was generated by Orris Medical AI for MD Medicine Examination preparation. "
    "Content is synthesized from authoritative medical textbooks. Clinical decisions should always "
    "be based on current guidelines and individual patient assessment.",
    ParagraphStyle("disclaimer", parent=body, fontSize=8.5, textColor=colors.grey,
                   alignment=TA_CENTER, fontName="Helvetica-Oblique")
))

# Build
doc.build(story)
print(f"PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/md-exam-notes && python generate_notes.py 2>&1

Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.

ok don’t create pdf just answer my question

Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.

ok dont make the pdf just gibe me the answer of the question

Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.
This is a shared conversation. Sign in to Orris to start your own chat.