powerpoint presentation for postgraduate internal medicine on Peptic ulcer disease make it as detailed as possible

Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Searching Images

peptic ulcer endoscopy gastric duodenal

Gastrointestinal fiberscopy image of the duodenal bulb demonstrating a large, irregular ulcer on the posterior wall. The ulcer is characterized by a prominent white-to-yellowish fibrin base, consistent with an active stage (A1 according to the Sakita-Miwa classification). The lesion stands in sharp contrast to the surrounding duodenal mucosa, which appears erythematous and edematous with irregular contours and loss of normal mucosal texture. Visible clear fluid bubbles are scattered across the mucosal surface, likely representing gastric or duodenal secretions. The image illustrates a significant peptic ulcer in a clinical case complicated by perforation and subsequent intra-abdominal abscess formation. This visual is suitable for educational purposes regarding upper gastrointestinal endoscopy, peptic ulcer disease (PUD) morphology, and Sakita-Miwa staging.

Gastrointestinal fiberscopy image of the duodenal bulb demonstrating a large, irregular ulcer on the posterior wall. The ulcer is characterized by a prominent white-to-yellowish fibrin base, consistent with an active stage (A1 according to the Sakita-Miwa classification). The lesion stands in sharp contrast to the surrounding duodenal mucosa, which appears erythematous and edematous with irregular contours and loss of normal mucosal texture. Visible clear fluid bubbles are scattered across the mucosal surface, likely representing gastric or duodenal secretions. The image illustrates a significant peptic ulcer in a clinical case complicated by perforation and subsequent intra-abdominal abscess formation. This visual is suitable for educational purposes regarding upper gastrointestinal endoscopy, peptic ulcer disease (PUD) morphology, and Sakita-Miwa staging.

This set of three clinical endoscopic photographs illustrates the appearance of the upper gastrointestinal mucosa in the stomach and duodenal cap. Panel A shows the stomach lining under white light endoscopy, characterized by a smooth, reddish-pink mucosal surface with visible fine submucosal vascular patterns. Panel B demonstrates the same gastric area using chromoendoscopy with indigo-carmine dye. The blue contrast agent accumulates in the mucosal pits and crevices, highlighting the surface micro-architecture, mucosal folds, and subtle irregularities that may indicate previous pathology like healed peptic ulcer scars. Panel C provides a white light view of the duodenal cap, showing a similar pinkish hue but with more pronounced anatomical folds compared to the gastric body. The image set is designed for gastroenterology education to demonstrate the utility of chromoendoscopy in enhancing mucosal detail and identifying chronic changes or scars from previous peptic ulcer disease (PUD) that might be subtle under standard white light imaging.

This set of three clinical endoscopic photographs illustrates the appearance of the upper gastrointestinal mucosa in the stomach and duodenal cap. Panel A shows the stomach lining under white light endoscopy, characterized by a smooth, reddish-pink mucosal surface with visible fine submucosal vascular patterns. Panel B demonstrates the same gastric area using chromoendoscopy with indigo-carmine dye. The blue contrast agent accumulates in the mucosal pits and crevices, highlighting the surface micro-architecture, mucosal folds, and subtle irregularities that may indicate previous pathology like healed peptic ulcer scars. Panel C provides a white light view of the duodenal cap, showing a similar pinkish hue but with more pronounced anatomical folds compared to the gastric body. The image set is designed for gastroenterology education to demonstrate the utility of chromoendoscopy in enhancing mucosal detail and identifying chronic changes or scars from previous peptic ulcer disease (PUD) that might be subtle under standard white light imaging.

This composite clinical diagnostic image features three endoscopic frames (g, h, i) obtained via Magnetically Controlled Capsule Endoscopy (MACE), demonstrating various upper gastrointestinal organic lesions. Image (g) depicts a fundic gland polyp within the stomach, appearing as a small, smooth, rounded sessile protrusion from the reddish-brown mucosal wall. Image (h) shows the duodenal bulb containing a duodenal ulcer, characterized by a localized area of mucosal depression and pale fibrinoid coating amidst surrounding erythematous tissue. Image (i) focuses on the Ampulla of Vater showing suspicious adenomatous changes, visualized as a complex, multi-lobulated, and nodular structure with variegated yellow-red coloration and irregular surface texture compared to the surrounding duodenal mucosa. These images serve as educational examples of common and significant gastric and duodenal findings in geriatric patients, emphasizing the utility of capsule endoscopy in identifying benign polyps, peptic ulcer disease, and potentially premalignant anatomical changes in the periampullary region.

This composite clinical diagnostic image features three endoscopic frames (g, h, i) obtained via Magnetically Controlled Capsule Endoscopy (MACE), demonstrating various upper gastrointestinal organic lesions. Image (g) depicts a fundic gland polyp within the stomach, appearing as a small, smooth, rounded sessile protrusion from the reddish-brown mucosal wall. Image (h) shows the duodenal bulb containing a duodenal ulcer, characterized by a localized area of mucosal depression and pale fibrinoid coating amidst surrounding erythematous tissue. Image (i) focuses on the Ampulla of Vater showing suspicious adenomatous changes, visualized as a complex, multi-lobulated, and nodular structure with variegated yellow-red coloration and irregular surface texture compared to the surrounding duodenal mucosa. These images serve as educational examples of common and significant gastric and duodenal findings in geriatric patients, emphasizing the utility of capsule endoscopy in identifying benign polyps, peptic ulcer disease, and potentially premalignant anatomical changes in the periampullary region.

A composite of nine endoscopic images (labeled A-I) illustrating the diverse clinical manifestations of Helicobacter pylori-associated gastritis and peptic ulcer disease within the gastric and duodenal mucosa. The images provide a comparative overview of mucosal pathology: (A) demonstrates mucosal erosion with punctate dark lesions; (B) shows adherent sticky mucus appearing as whitish-yellow patches; (C) illustrates diffuse mucosal erythema; (D) depicts antral gastritis with generalized hyperemia; (E) highlights spotty redness across the mucosal surface; (F) reveals a duodenal ulcer with surrounding inflammatory changes; (G) displays classic nodular gastritis characterized by a uniform, 'cobblestone' or granular mucosal texture; (H) shows a gastric ulcer with evidence of active erosion; and (I) exhibits hypertrophic gastropathy with significantly enlarged rugal folds. This educational compilation is essential for gastroenterology training to differentiate specific morphological patterns such as nodularity, erosions, and fold thickening during diagnostic upper gastrointestinal endoscopy.

A composite of nine endoscopic images (labeled A-I) illustrating the diverse clinical manifestations of Helicobacter pylori-associated gastritis and peptic ulcer disease within the gastric and duodenal mucosa. The images provide a comparative overview of mucosal pathology: (A) demonstrates mucosal erosion with punctate dark lesions; (B) shows adherent sticky mucus appearing as whitish-yellow patches; (C) illustrates diffuse mucosal erythema; (D) depicts antral gastritis with generalized hyperemia; (E) highlights spotty redness across the mucosal surface; (F) reveals a duodenal ulcer with surrounding inflammatory changes; (G) displays classic nodular gastritis characterized by a uniform, 'cobblestone' or granular mucosal texture; (H) shows a gastric ulcer with evidence of active erosion; and (I) exhibits hypertrophic gastropathy with significantly enlarged rugal folds. This educational compilation is essential for gastroenterology training to differentiate specific morphological patterns such as nodularity, erosions, and fold thickening during diagnostic upper gastrointestinal endoscopy.

A composite panel of seventeen high-definition gastroscopy images illustrating common endoscopic features of the gastric and duodenal mucosa, categorized according to the Sydney System for gastritis. The images demonstrate variations in mucosal vascularity and inflammation, including diffuse redness (2), spotty redness (3), and patchy redness (4). Specific vascular patterns are shown through the Regular Arrangement of Collecting venules (RAC) in both conventional (8a-1) and magnifying endoscopy (8a-2). Pathological findings include mucus adhesion (1), enlarged rugal folds (5), mucosal edema (6), xanthoma (9), and various polyps such as fundic gland (10) and hyperplastic types (11). Ulcerative lesions are represented by gastric (12) and duodenal (13) ulcers. A detailed series on erosions (14a-d) compares flat, raised, hemorrhagic, and punctate bleeding spot morphologies. This comparison chart serves as an educational reference for gastroenterologists to differentiate between normal mucosal variants, Helicobacter pylori-associated changes, and peptic ulcer disease.

A composite panel of seventeen high-definition gastroscopy images illustrating common endoscopic features of the gastric and duodenal mucosa, categorized according to the Sydney System for gastritis. The images demonstrate variations in mucosal vascularity and inflammation, including diffuse redness (2), spotty redness (3), and patchy redness (4). Specific vascular patterns are shown through the Regular Arrangement of Collecting venules (RAC) in both conventional (8a-1) and magnifying endoscopy (8a-2). Pathological findings include mucus adhesion (1), enlarged rugal folds (5), mucosal edema (6), xanthoma (9), and various polyps such as fundic gland (10) and hyperplastic types (11). Ulcerative lesions are represented by gastric (12) and duodenal (13) ulcers. A detailed series on erosions (14a-d) compares flat, raised, hemorrhagic, and punctate bleeding spot morphologies. This comparison chart serves as an educational reference for gastroenterologists to differentiate between normal mucosal variants, Helicobacter pylori-associated changes, and peptic ulcer disease.

A composite medical image featuring diagnostic radiology and endoscopy of the upper gastrointestinal tract. Panel 1A is a coronal view from a contrast-enhanced computed tomography (CT) scan of the abdomen. It shows significant mural thickening of the proximal duodenum, highlighted by a yellow circle and annotated with a caliper measurement of 12.3mm. The surrounding anatomy, including the liver and right kidney, is visible. Panel 1B is an endoscopic photograph (gastroscopy) showing a clean-based antral ulcer extending into the duodenum. The image demonstrates a severe obstructing duodenal stricture, characterized by a narrow, distorted lumen and erythematous mucosal changes. These findings are clinically relevant for evaluating gastric outlet obstruction and differentiating between peptic ulcer disease and possible malignancy or IgG4-related disease in the proximal small bowel.

A composite medical image featuring diagnostic radiology and endoscopy of the upper gastrointestinal tract. Panel 1A is a coronal view from a contrast-enhanced computed tomography (CT) scan of the abdomen. It shows significant mural thickening of the proximal duodenum, highlighted by a yellow circle and annotated with a caliper measurement of 12.3mm. The surrounding anatomy, including the liver and right kidney, is visible. Panel 1B is an endoscopic photograph (gastroscopy) showing a clean-based antral ulcer extending into the duodenum. The image demonstrates a severe obstructing duodenal stricture, characterized by a narrow, distorted lumen and erythematous mucosal changes. These findings are clinically relevant for evaluating gastric outlet obstruction and differentiating between peptic ulcer disease and possible malignancy or IgG4-related disease in the proximal small bowel.

Reading File
Reading File
Reading File
Searching Images

H. pylori bacteria gastric mucosa histology

Reading File
Reading File
Searching Images

Helicobacter pylori gastric histology

Gastric biopsy histology showing acquired MALT following Helicobacter pylori infection. Hematoxylin and eosin stained sections reveal dense lymphoid infiltration in the lamina propria with formation of lymphoid aggregates and germinal centers, partially effacing normal mucosal architecture. The overlying gastric epithelium remains intact in areas, but lymphoepithelial lesions may be present, indicating invasion of ducts or epithelium by neoplastic B-cells. The stomach normally lacks organized lymphoid tissue; the observed lymphoid proliferation represents mucosa-associated lymphoid tissue expansion, consistent with extranodal marginal zone B-cell lymphoma of mucosa-associated lymphoid tissue (MALT lymphoma). The cellular population is typically small to medium-sized lymphocytes with irregular chromatin, sometimes with plasmacytoid differentiation; scattered immunoblasts may occur. Chronic inflammation, such as Helicobacter pylori gastritis, provides the antigenic stimulus driving MALT development and potential regression after microbial eradication. Clinically, MALT lymphoma of the stomach may respond to antibiotic therapy, with lesion regression upon H. pylori eradication, or require staging and systemic therapy if refractory or advanced. Differential includes reactive lymphoid hyperplasia and transformation to diffuse large B-cell lymphoma. Diagnostic significance lies in recognizing MALT patterns to guide treatment, prognosis, and surveillance; correlate with endoscopic findings and serology for infection status.

Gastric biopsy histology showing acquired MALT following Helicobacter pylori infection. Hematoxylin and eosin stained sections reveal dense lymphoid infiltration in the lamina propria with formation of lymphoid aggregates and germinal centers, partially effacing normal mucosal architecture. The overlying gastric epithelium remains intact in areas, but lymphoepithelial lesions may be present, indicating invasion of ducts or epithelium by neoplastic B-cells. The stomach normally lacks organized lymphoid tissue; the observed lymphoid proliferation represents mucosa-associated lymphoid tissue expansion, consistent with extranodal marginal zone B-cell lymphoma of mucosa-associated lymphoid tissue (MALT lymphoma). The cellular population is typically small to medium-sized lymphocytes with irregular chromatin, sometimes with plasmacytoid differentiation; scattered immunoblasts may occur. Chronic inflammation, such as Helicobacter pylori gastritis, provides the antigenic stimulus driving MALT development and potential regression after microbial eradication. Clinically, MALT lymphoma of the stomach may respond to antibiotic therapy, with lesion regression upon H. pylori eradication, or require staging and systemic therapy if refractory or advanced. Differential includes reactive lymphoid hyperplasia and transformation to diffuse large B-cell lymphoma. Diagnostic significance lies in recognizing MALT patterns to guide treatment, prognosis, and surveillance; correlate with endoscopic findings and serology for infection status.

This histopathology image shows gastric mucosa with chronic active gastritis. Hematoxylin and eosin (H&E) staining reveals dense lymphoplasmacytic infiltrate in the lamina propria surrounding gastric glands, with crypt abscess formation and neutrophilic cryptitis. Epithelial architecture is variably preserved, but focal glandular distortion and inflammatory debris are evident. There is a prominent inflammatory milieu dominated by mature lymphocytes and plasma cells, consistent with a chronic inflammatory process, and occasional eosinophils are present. The image is contextually linked to Helicobacter pylori infection, which is identified in a subsequent Giemsa-stained preparation in most cases and is a key driver of acquired MALT in the stomach. Gastric mucosa in H. pylori-associated gastritis may harbor mucosa-associated lymphoid tissue (MALT) and can evolve toward MALT lymphoma in rare cases. Clinically, such findings warrant H. pylori testing and eradication therapy, since antibiotic treatment often induces remission in gastric MALT lymphoma and reduces cancer risk. This field illustrates the histologic substrate for chronic inflammation and B-cell-mediated lymphoid responses; correlation with clinical data, endoscopy, and ancillary studies (immunohistochemistry, molecular tests) is essential for accurate diagnosis and management decisions. The image is suitable for teaching histology of gastritis, differential diagnosis of gastric ulcers, and evaluation of H. pylori-related MALT pathology in practice.

This histopathology image shows gastric mucosa with chronic active gastritis. Hematoxylin and eosin (H&E) staining reveals dense lymphoplasmacytic infiltrate in the lamina propria surrounding gastric glands, with crypt abscess formation and neutrophilic cryptitis. Epithelial architecture is variably preserved, but focal glandular distortion and inflammatory debris are evident. There is a prominent inflammatory milieu dominated by mature lymphocytes and plasma cells, consistent with a chronic inflammatory process, and occasional eosinophils are present. The image is contextually linked to Helicobacter pylori infection, which is identified in a subsequent Giemsa-stained preparation in most cases and is a key driver of acquired MALT in the stomach. Gastric mucosa in H. pylori-associated gastritis may harbor mucosa-associated lymphoid tissue (MALT) and can evolve toward MALT lymphoma in rare cases. Clinically, such findings warrant H. pylori testing and eradication therapy, since antibiotic treatment often induces remission in gastric MALT lymphoma and reduces cancer risk. This field illustrates the histologic substrate for chronic inflammation and B-cell-mediated lymphoid responses; correlation with clinical data, endoscopy, and ancillary studies (immunohistochemistry, molecular tests) is essential for accurate diagnosis and management decisions. The image is suitable for teaching histology of gastritis, differential diagnosis of gastric ulcers, and evaluation of H. pylori-related MALT pathology in practice.

High-power gastric mucosal biopsy prepared for light microscopy with cyclin D1 immunohistochemistry demonstrates features characteristic of extranodal marginal zone B‑cell lymphoma of MALT type involving the stomach. In this specimen, a dense, monomorphic infiltrate of small to medium-sized lymphocytes expands the lamina propria and surrounds gastric glands, forming classic lymphoepithelial lesions. The neoplastic cells typically exhibit irregular, slightly indented nuclei with scant cytoplasm and inconspicuous nucleoli; plasmacytoid differentiation may be present in focal areas. Immunohistochemical staining is negative for cyclin D1, supporting a MALT phenotype and helping distinguish from mantle cell lymphoma, which is cyclin D1 positive. The neoplastic cells reliably express B‑cell markers (CD20/CD79a) and often show light-chain restriction, consistent with a monoclonal B‑cell population arising in mucosa‑associated lymphoid tissue. Background reactive lymphoid infiltrates and H. pylori–associated gastritis can accompany the neoplasm. Clinically, MALT lymphoma of the stomach is frequently associated with Helicobacter pylori infection and is potentially amenable to antibiotic eradication therapy, with response rates correlating with stage and H. pylori status. Radiologic and endoscopic correlation may reveal regional gastric wall involvement but histology remains essential for diagnosis, grading, and staging. This image underlines the diagnostic utility of cyclin D1 negativity in differentiating gastric MALT lymphoma from cyclin D1‑positive mantle cell lymphoma.

High-power gastric mucosal biopsy prepared for light microscopy with cyclin D1 immunohistochemistry demonstrates features characteristic of extranodal marginal zone B‑cell lymphoma of MALT type involving the stomach. In this specimen, a dense, monomorphic infiltrate of small to medium-sized lymphocytes expands the lamina propria and surrounds gastric glands, forming classic lymphoepithelial lesions. The neoplastic cells typically exhibit irregular, slightly indented nuclei with scant cytoplasm and inconspicuous nucleoli; plasmacytoid differentiation may be present in focal areas. Immunohistochemical staining is negative for cyclin D1, supporting a MALT phenotype and helping distinguish from mantle cell lymphoma, which is cyclin D1 positive. The neoplastic cells reliably express B‑cell markers (CD20/CD79a) and often show light-chain restriction, consistent with a monoclonal B‑cell population arising in mucosa‑associated lymphoid tissue. Background reactive lymphoid infiltrates and H. pylori–associated gastritis can accompany the neoplasm. Clinically, MALT lymphoma of the stomach is frequently associated with Helicobacter pylori infection and is potentially amenable to antibiotic eradication therapy, with response rates correlating with stage and H. pylori status. Radiologic and endoscopic correlation may reveal regional gastric wall involvement but histology remains essential for diagnosis, grading, and staging. This image underlines the diagnostic utility of cyclin D1 negativity in differentiating gastric MALT lymphoma from cyclin D1‑positive mantle cell lymphoma.

Reading File
Reading File
Searching Images

perforated peptic ulcer surgical treatment

Running Command

mkdir -p /tmp/workspace/pud-presentation && ls /tmp/workspace/

Writing File

~/pud-presentation/build_pud.py

import json
import subprocess
import base64
from io import BytesIO
from pptx import Presentation
from pptx.util import Inches, Pt, Emu
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
from pptx.util import Inches, Pt
import os

# ── Colour palette ──────────────────────────────────────────────
DARK_NAVY   = RGBColor(0x0D, 0x2B, 0x45)   # slide backgrounds / headers
MED_BLUE    = RGBColor(0x1A, 0x57, 0x8C)   # accent boxes
LIGHT_BLUE  = RGBColor(0xD6, 0xE8, 0xF7)   # content box backgrounds
ORANGE      = RGBColor(0xE8, 0x6A, 0x1A)   # highlight / key points
WHITE       = RGBColor(0xFF, 0xFF, 0xFF)
LIGHT_GRAY  = RGBColor(0xF2, 0xF5, 0xF9)
DARK_TEXT   = RGBColor(0x1A, 0x1A, 0x2E)
YELLOW_HL   = RGBColor(0xFF, 0xE0, 0x80)
GREEN       = RGBColor(0x17, 0x7E, 0x4E)
RED         = RGBColor(0xC0, 0x39, 0x2B)

prs = Presentation()
prs.slide_width  = Inches(13.333)
prs.slide_height = Inches(7.5)
blank_layout = prs.slide_layouts[6]   # fully blank

# ── Helper utilities ────────────────────────────────────────────
def add_rect(slide, x, y, w, h, fill_rgb, alpha=None):
    shape = slide.shapes.add_shape(1, Inches(x), Inches(y), Inches(w), Inches(h))
    shape.line.fill.background()
    shape.fill.solid()
    shape.fill.fore_color.rgb = fill_rgb
    return shape

def add_text(slide, text, x, y, w, h,
             font_size=18, bold=False, italic=False, color=WHITE,
             align=PP_ALIGN.LEFT, v_anchor=MSO_ANCHOR.TOP, wrap=True,
             font_name="Calibri"):
    tb = slide.shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
    tf = tb.text_frame
    tf.word_wrap = wrap
    tf.vertical_anchor = v_anchor
    tf.margin_left = Inches(0.05)
    tf.margin_right = Inches(0.05)
    tf.margin_top = Inches(0.03)
    tf.margin_bottom = Inches(0.03)
    p = tf.paragraphs[0]
    p.alignment = align
    run = p.add_run()
    run.text = text
    run.font.name = font_name
    run.font.size = Pt(font_size)
    run.font.bold = bold
    run.font.italic = italic
    run.font.color.rgb = color
    return tb

def add_multi_bullet(slide, items, x, y, w, h,
                     font_size=15, color=DARK_TEXT, bold_first=False,
                     bullet_char="▸ ", line_spacing=1.2):
    """items = list of (indent_level, text, bold) tuples or plain strings."""
    tb = slide.shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
    tf = tb.text_frame
    tf.word_wrap = True
    tf.vertical_anchor = MSO_ANCHOR.TOP
    tf.margin_left = Inches(0.1)
    tf.margin_right = Inches(0.05)
    tf.margin_top = Inches(0.05)
    tf.margin_bottom = Inches(0.05)

    first = True
    for item in items:
        if isinstance(item, str):
            lvl, text, bold = 0, item, False
        else:
            lvl, text, bold = item

        if first:
            p = tf.paragraphs[0]
            first = False
        else:
            p = tf.add_paragraph()

        p.space_before = Pt(2)
        p.space_after  = Pt(1)
        indent_str = "    " * lvl
        run = p.add_run()
        run.text = indent_str + bullet_char + text
        run.font.name = "Calibri"
        run.font.size = Pt(font_size)
        run.font.bold = bold
        run.font.color.rgb = color
    return tb

def slide_header(slide, title, subtitle=None,
                 bg_color=DARK_NAVY, title_color=WHITE, sub_color=YELLOW_HL):
    """Full-width dark header bar at top."""
    bar_h = 1.0 if subtitle else 0.85
    add_rect(slide, 0, 0, 13.333, bar_h, bg_color)
    add_text(slide, title, 0.25, 0.05, 12.8, 0.65,
             font_size=28, bold=True, color=title_color,
             align=PP_ALIGN.LEFT, v_anchor=MSO_ANCHOR.MIDDLE)
    if subtitle:
        add_text(slide, subtitle, 0.25, 0.65, 12.8, 0.35,
                 font_size=14, italic=True, color=sub_color,
                 align=PP_ALIGN.LEFT)

def section_box(slide, title, x, y, w, h,
                title_color=WHITE, box_color=MED_BLUE, content_color=LIGHT_BLUE):
    """Coloured section header + lighter content area."""
    add_rect(slide, x, y, w, 0.38, box_color)
    add_text(slide, title, x+0.1, y+0.02, w-0.2, 0.34,
             font_size=14, bold=True, color=title_color,
             align=PP_ALIGN.LEFT, v_anchor=MSO_ANCHOR.MIDDLE)
    add_rect(slide, x, y+0.38, w, h-0.38, content_color)

def fetch_img(url):
    try:
        result = json.loads(subprocess.check_output(
            ["python", "/tmp/skills/shared/scripts/fetch_images.py", url],
            timeout=30
        ))
        if result and result[0].get("base64"):
            b64 = result[0]["base64"]
            if "," in b64:
                b64 = b64.split(",", 1)[1]
            return BytesIO(base64.b64decode(b64))
    except Exception as e:
        print(f"  Image fetch failed for {url}: {e}")
    return None

def add_image(slide, url, x, y, w, h=None):
    img_io = fetch_img(url)
    if img_io:
        try:
            if h:
                pic = slide.shapes.add_picture(img_io, Inches(x), Inches(y),
                                               width=Inches(w), height=Inches(h))
            else:
                pic = slide.shapes.add_picture(img_io, Inches(x), Inches(y), width=Inches(w))
            return pic
        except Exception as e:
            print(f"  Could not embed image: {e}")
    return None

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 1  – Title slide
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, DARK_NAVY)
# Decorative accent stripe
add_rect(s, 0, 3.5, 13.333, 0.08, ORANGE)
add_rect(s, 0, 3.58, 13.333, 0.04, MED_BLUE)

add_text(s, "PEPTIC ULCER DISEASE",
         0.8, 1.2, 11.8, 1.8,
         font_size=48, bold=True, color=WHITE,
         align=PP_ALIGN.CENTER, v_anchor=MSO_ANCHOR.MIDDLE)
add_text(s, "A Comprehensive Postgraduate Review",
         0.8, 2.85, 11.8, 0.7,
         font_size=22, italic=True, color=YELLOW_HL,
         align=PP_ALIGN.CENTER)
add_text(s, "Department of Internal Medicine  |  Postgraduate Teaching Series",
         0.8, 3.85, 11.8, 0.5,
         font_size=16, color=LIGHT_BLUE, align=PP_ALIGN.CENTER)
add_text(s, "Sources: Schwartz's Surgery 11e · Sleisenger & Fordtran 11e · Bailey & Love 28e\n"
            "Robbins & Kumar Basic Pathology · Yamada's Gastroenterology 7e",
         0.8, 6.5, 11.8, 0.7,
         font_size=11, italic=True, color=RGBColor(0xAA, 0xBB, 0xCC),
         align=PP_ALIGN.CENTER)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 2  – Table of Contents / Lecture Outline
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Lecture Outline", "What we will cover today")

topics_left = [
    "1. Definition & Historical Perspective",
    "2. Epidemiology & Burden of Disease",
    "3. Anatomy & Pathology",
    "4. Pathophysiology – Mucosal Balance",
    "5. Aetiology – H. pylori",
    "6. Aetiology – NSAIDs",
    "7. Other Risk Factors",
]
topics_right = [
    "8. Clinical Presentation & Symptoms",
    "9. Investigations & Diagnosis",
    "10. Complications – Bleeding",
    "11. Complications – Perforation",
    "12. Complications – Obstruction",
    "13. Medical Management",
    "14. H. pylori Eradication Regimens",
    "15. Surgical Management",
    "16. Special Situations & Follow-up",
]
add_rect(s, 0.4, 1.05, 6.0, len(topics_left)*0.5+0.2, MED_BLUE)
for i, t in enumerate(topics_left):
    add_text(s, t, 0.55, 1.1 + i*0.5, 5.7, 0.48,
             font_size=15, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)

add_rect(s, 6.8, 1.05, 6.1, len(topics_right)*0.5+0.2, DARK_NAVY)
for i, t in enumerate(topics_right):
    add_text(s, t, 6.95, 1.1 + i*0.5, 5.8, 0.48,
             font_size=15, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 3  – Definition & Historical Background
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Definition & Historical Background")

add_rect(s, 0.4, 1.1, 12.5, 1.8, WHITE)
add_rect(s, 0.4, 1.1, 0.08, 1.8, ORANGE)
add_text(s, "Definition",
         0.6, 1.12, 12.0, 0.45, font_size=15, bold=True, color=DARK_NAVY)
add_text(s,
    "Peptic Ulcer Disease (PUD) is a breach in the mucosal lining of the gastrointestinal tract extending "
    "through the muscularis mucosae into the submucosa or deeper, occurring in areas exposed to acid "
    "and pepsin — most commonly the gastric antrum and first portion of the duodenum.",
    0.6, 1.58, 12.0, 1.3, font_size=15, color=DARK_TEXT, wrap=True)

add_rect(s, 0.4, 3.1, 12.5, 3.8, WHITE)
add_rect(s, 0.4, 3.1, 0.08, 3.8, MED_BLUE)
add_text(s, "Historical Milestones", 0.6, 3.12, 11.0, 0.45,
         font_size=15, bold=True, color=DARK_NAVY)
hist = [
    (0, "1800s: Peptic ulcer recognised as a distinct clinical entity; acid implicated", False),
    (0, "1910: Schwartz popularises 'no acid, no ulcer' dictum", False),
    (0, "1938: Mann & Williamson: vagotomy shown to reduce acid and heal ulcers", False),
    (0, "1976: Introduction of H2-receptor antagonists (cimetidine) — first major medical therapy", False),
    (0, "1983: Barry Marshall & Robin Warren identify Helicobacter pylori — Nobel Prize 2005", False),
    (0, "1989: Proton pump inhibitors (omeprazole) introduced — paradigm shift in acid suppression", False),
    (0, "1990s–present: H. pylori eradication transforms PUD from chronic relapsing to curable disease", False),
]
add_multi_bullet(s, hist, 0.6, 3.6, 12.0, 3.2, font_size=14, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 4  – Epidemiology
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Epidemiology & Burden of Disease",
             "Global prevalence, trends, and risk demographics")

# Left column
section_box(s, "Global Burden", 0.4, 1.05, 6.0, 3.4)
epi_left = [
    "Lifetime risk: ~10% males, ~4% females (USA)",
    "~4 million individuals treated annually in the USA",
    "~100,000 hospitalisations/year for bleeding PUD",
    "DU more common than GU (4:1 ratio)",
    "Peak incidence shifting to older age groups",
    "Gender gap narrowing — hormonal/lifestyle factors",
    "Rising incidence in resource-poor nations",
]
add_multi_bullet(s, epi_left, 0.55, 1.5, 5.7, 2.8, font_size=13, color=DARK_TEXT)

section_box(s, "Temporal Trends", 6.7, 1.05, 6.2, 3.4)
epi_right = [
    "Marked decline in elective surgery since 1990s",
    "Reduction in DU incidence correlates with ↓ H. pylori",
    "Increasing GU: driven by aging + NSAID/aspirin use",
    "Emergency surgery for complications persists",
    "30-day mortality: bleeding ulcer ~5–10%",
    "Mortality higher in elderly and those with comorbidities",
]
add_multi_bullet(s, epi_right, 6.85, 1.5, 5.9, 2.8, font_size=13, color=DARK_TEXT)

# Key stat boxes
add_rect(s, 0.4, 4.55, 3.8, 1.4, ORANGE)
add_text(s, "70–90%", 0.4, 4.58, 3.8, 0.7, font_size=36, bold=True,
         color=WHITE, align=PP_ALIGN.CENTER)
add_text(s, "of DU associated\nwith H. pylori", 0.4, 5.2, 3.8, 0.7,
         font_size=14, color=WHITE, align=PP_ALIGN.CENTER)

add_rect(s, 4.5, 4.55, 3.8, 1.4, MED_BLUE)
add_text(s, "50–60%", 4.5, 4.58, 3.8, 0.7, font_size=36, bold=True,
         color=WHITE, align=PP_ALIGN.CENTER)
add_text(s, "of GU associated\nwith NSAIDs", 4.5, 5.2, 3.8, 0.7,
         font_size=14, color=WHITE, align=PP_ALIGN.CENTER)

add_rect(s, 8.6, 4.55, 4.3, 1.4, GREEN)
add_text(s, "~5–10%", 8.6, 4.58, 4.3, 0.7, font_size=36, bold=True,
         color=WHITE, align=PP_ALIGN.CENTER)
add_text(s, "30-day mortality\nin bleeding PUD", 8.6, 5.2, 4.3, 0.7,
         font_size=14, color=WHITE, align=PP_ALIGN.CENTER)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 5  – Anatomy & Sites
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Anatomy & Common Sites of Ulceration")

add_rect(s, 0.4, 1.05, 8.0, 5.9, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 5.9, MED_BLUE)
add_text(s, "Common Sites", 0.6, 1.08, 7.6, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
sites = [
    (0, "DUODENUM (most common): First part (D1) — 95% of duodenal ulcers", True),
    (1, "Anterior wall: tend to PERFORATE", False),
    (1, "Posterior wall: tend to BLEED (erosion of gastroduodenal artery)", False),
    (1, "\"Kissing ulcers\": simultaneous anterior + posterior", False),
    (0, "STOMACH:", True),
    (1, "Lesser curve (most common gastric site)", False),
    (1, "Gastric antrum (prepyloric)", False),
    (1, "Gastric body", False),
    (1, "Cardia/GOJ — increasing incidence (exclude malignancy)", False),
    (0, "UNCOMMON / SPECIAL SITES:", True),
    (1, "Oesophagus — GERD-related / Barrett's ulcer", False),
    (1, "Stomal ulcer — post gastroenterostomy or Billroth II (jejunal side)", False),
    (1, "Meckel's diverticulum — ectopic gastric mucosa", False),
    (1, "Jejunum — Zollinger–Ellison syndrome (ZES)", False),
    (0, "Key rule: Ulcer forms at junction between different epithelial types — least acid-resistant tissue", False),
]
add_multi_bullet(s, sites, 0.6, 1.55, 7.7, 5.3, font_size=13, color=DARK_TEXT)

# Right side: Johnson classification of gastric ulcers
add_rect(s, 8.7, 1.05, 4.2, 5.9, DARK_NAVY)
add_text(s, "Johnson Classification\nof Gastric Ulcers", 8.85, 1.08, 4.0, 0.8,
         font_size=14, bold=True, color=YELLOW_HL, align=PP_ALIGN.CENTER)
johnson = [
    "Type I: Lesser curve, body\n(↓ acid, mucosal defect)",
    "Type II: Gastric body +\nduodenal ulcer (↑ acid)",
    "Type III: Prepyloric\n(↑ acid, like DU)",
    "Type IV: High on lesser\ncurve near GOJ",
    "Type V: Any site\n(NSAID-induced)",
]
colors_j = [WHITE, YELLOW_HL, WHITE, YELLOW_HL, WHITE]
for i, (jt, jc) in enumerate(zip(johnson, colors_j)):
    ypos = 2.05 + i * 0.9
    add_rect(s, 8.85, ypos, 3.9, 0.82, MED_BLUE if i%2==0 else RGBColor(0x14, 0x45, 0x70))
    add_text(s, jt, 8.95, ypos+0.03, 3.7, 0.78,
             font_size=12, color=jc, v_anchor=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 6  – Pathophysiology
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Pathophysiology",
             "The balance between aggressive & defensive forces")

# Balance diagram
add_rect(s, 0.4, 1.1, 5.8, 2.9, RED)
add_text(s, "⚠  AGGRESSIVE FACTORS", 0.5, 1.12, 5.6, 0.5,
         font_size=16, bold=True, color=WHITE, align=PP_ALIGN.CENTER)
aggressive = [
    "Hydrochloric acid (HCl) — parietal cells",
    "Pepsin — chief cells (requires acid activation)",
    "H. pylori — ammonia, proteases, cytotoxins",
    "NSAIDs — direct and indirect injury",
    "Bile reflux",
    "Alcohol, tobacco",
]
add_multi_bullet(s, aggressive, 0.5, 1.65, 5.6, 2.2, font_size=13, color=WHITE)

add_rect(s, 7.1, 1.1, 5.8, 2.9, GREEN)
add_text(s, "🛡  DEFENSIVE FACTORS", 7.2, 1.12, 5.6, 0.5,
         font_size=16, bold=True, color=WHITE, align=PP_ALIGN.CENTER)
defensive = [
    "Mucous layer — bicarbonate-rich gel",
    "Epithelial tight junctions — barrier function",
    "Mucosal blood flow — delivers O₂, buffers H⁺",
    "Prostaglandins E₂ & I₂ — stimulate mucus/bicarb",
    "Epithelial restitution — rapid surface repair",
    "Growth factors (EGF, TGF-α)",
]
add_multi_bullet(s, defensive, 7.2, 1.65, 5.6, 2.2, font_size=13, color=WHITE)

# Equation
add_rect(s, 0.4, 4.1, 12.5, 0.5, ORANGE)
add_text(s,
    "ULCER  =  Aggressive Factors  >  Defensive Factors  (imbalance in either direction causes mucosal breakdown)",
    0.5, 4.12, 12.3, 0.44, font_size=14, bold=True, color=WHITE, align=PP_ALIGN.CENTER,
    v_anchor=MSO_ANCHOR.MIDDLE)

add_rect(s, 0.4, 4.7, 12.5, 2.65, WHITE)
add_rect(s, 0.4, 4.7, 0.08, 2.65, ORANGE)
add_text(s, "Acid Secretion Physiology (key for pharmacology)", 0.6, 4.72, 12.0, 0.42,
         font_size=14, bold=True, color=DARK_NAVY)
phys = [
    "Parietal cell stimulants: Gastrin (G-cells, antrum), ACh (vagal), Histamine (ECL cells) → activate H⁺/K⁺-ATPase pump",
    "Gastrin release: stimulated by protein, distension, vagal tone; inhibited by low antral pH via somatostatin (D cells)",
    "H. pylori depletes antral somatostatin → ↑ gastrin → ↑ acid → parietal cell hyperplasia (DU pathway)",
    "Zollinger-Ellison syndrome: gastrin-secreting tumour → massive acid → multiple/atypical ulcers",
    "NSAIDs: inhibit COX-1 → ↓ prostaglandins → ↓ mucus/bicarb/blood flow; also direct mucosal topical injury",
]
add_multi_bullet(s, phys, 0.6, 5.15, 12.0, 2.1, font_size=12.5, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 7  – H. pylori Aetiology
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "H. pylori — The Primary Causative Agent",
             "Discovered 1983 · Nobel Prize 2005 · Transforms PUD natural history")

add_rect(s, 0.4, 1.05, 7.8, 6.3, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 6.3, MED_BLUE)
add_text(s, "Key Facts About H. pylori", 0.6, 1.08, 7.5, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
hp = [
    (0, "Gram-negative, spiral-shaped, flagellated microaerophilic rod", False),
    (0, "Colonises gastric antrum preferentially; survives by urease-mediated NH₃ production → neutralises acid", False),
    (0, "Infects >50% of the world's population; higher in developing countries (>80%)", False),
    (0, "Transmission: faeco-oral, oral-oral; childhood acquisition most common", False),
    (0, "Virulence factors:", True),
    (1, "Urease → NH₃ → mucosal injury + alkalinises microenvironment", False),
    (1, "CagA (cytotoxin-associated gene A) — injected via T4SS, disrupts cell signalling, ↑ cancer risk", False),
    (1, "VacA (vacuolating cytotoxin A) — induces vacuolation, apoptosis, immune evasion", False),
    (1, "OipA, BabA — outer membrane proteins, adhesion", False),
    (0, "Mechanism in DU: antral gastritis → ↓ somatostatin D cells → ↑ gastrin → ↑ parietal cell mass → hyperacidity → duodenal gastric metaplasia → H. pylori colonises duodenum → ↑ DU risk 50-fold", False),
    (0, "90% of DU patients are H. pylori positive", False),
    (0, "70% of GU patients are H. pylori positive", False),
    (0, "Curing H. pylori: reduces ulcer recurrence from >75% → <20% (multiple RCTs)", False),
    (0, "Association: low-grade gastric MALT lymphoma, gastric adenocarcinoma (Class I carcinogen)", False),
]
add_multi_bullet(s, hp, 0.6, 1.55, 7.6, 5.7, font_size=12.5, color=DARK_TEXT)

# Right: image placeholder + diagnosis panel
add_image(s,
    "https://cdn.orris.care/cdss_images/Pathology_1760047119073_99ab0840-08f9-4a89-92d7-23c5c6144c82.jpg",
    8.45, 1.05, 4.5, 3.0)
add_text(s, "H. pylori-associated chronic active gastritis\n(H&E — dense lymphoplasmacytic infiltrate)",
         8.45, 4.1, 4.5, 0.6, font_size=10, italic=True, color=DARK_TEXT, align=PP_ALIGN.CENTER)

add_rect(s, 8.45, 4.75, 4.5, 2.6, DARK_NAVY)
add_text(s, "Testing for H. pylori", 8.55, 4.78, 4.3, 0.42,
         font_size=14, bold=True, color=YELLOW_HL)
tests = [
    "NON-INVASIVE:",
    "• Urea Breath Test (UBT) — best accuracy",
    "• Stool antigen test (SAT) — cost-effective",
    "• Serology (IgG) — cannot confirm active",
    "INVASIVE (endoscopy):",
    "• Rapid urease test (CLO test)",
    "• Histology ± Giemsa stain",
    "• Culture (for resistance testing)",
]
y_off = 5.22
for t in tests:
    bld = ":" in t and not t.startswith("•")
    add_text(s, t, 8.55, y_off, 4.3, 0.34,
             font_size=11, bold=bld, color=WHITE if not bld else YELLOW_HL)
    y_off += 0.3

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 8  – NSAIDs
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "NSAIDs & Aspirin — Second Major Cause",
             "Mechanism · Risk stratification · Prevention strategies")

add_rect(s, 0.4, 1.05, 7.9, 6.35, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 6.35, RED)
add_text(s, "NSAID-Induced Mucosal Injury", 0.6, 1.08, 7.6, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
nsaid = [
    (0, "MECHANISM — Dual injury:", True),
    (1, "Systemic: COX-1 inhibition → ↓ PGE₂, PGI₂ → ↓ mucus, bicarb, mucosal blood flow", False),
    (1, "Topical: direct epithelial injury (weakly acidic, accumulate in cells, uncouple oxidative phosphorylation)", False),
    (0, "All NSAIDs (incl. low-dose aspirin) increase GI risk; selectivity varies:", True),
    (1, "Traditional NSAIDs (e.g. ibuprofen, naproxen, diclofenac) — high risk", False),
    (1, "COX-2 selective (e.g. celecoxib) — lower GI risk but ↑ CV risk", False),
    (1, "Low-dose aspirin — still carries significant GI risk even at 75–150 mg/day", False),
    (0, "GI risk factors for NSAID users:", True),
    (1, "Age >65, prior PUD/GI bleed, H. pylori co-infection", False),
    (1, "Concomitant corticosteroids, anticoagulants, dual antiplatelet therapy", False),
    (1, "High-dose or multiple NSAIDs", False),
    (0, "Prevention strategies:", True),
    (1, "Use lowest effective dose for shortest duration", False),
    (1, "Co-prescribe PPI (preferred) or misoprostol in high-risk patients", False),
    (1, "Test and treat H. pylori before starting long-term NSAIDs", False),
    (1, "Switch to COX-2 selective agent where CV risk permits", False),
    (0, "MUCOSA trial: misoprostol ↓ complicated UGI events by 53% vs NSAID alone", False),
    (0, "VIGOR trial: rofecoxib ↓ GI events by 54% vs naproxen", False),
]
add_multi_bullet(s, nsaid, 0.6, 1.55, 7.7, 5.7, font_size=12, color=DARK_TEXT)

# Right column
add_rect(s, 8.6, 1.05, 4.35, 3.0, DARK_NAVY)
add_text(s, "Risk Stratification\n(GI Risk × CV Risk Matrix)",
         8.75, 1.08, 4.1, 0.65, font_size=14, bold=True, color=YELLOW_HL)
matrix = [
    ("LOW GI risk", "LOW CV", "NSAID alone"),
    ("LOW GI risk", "HIGH CV", "Naproxen + PPI"),
    ("HIGH GI risk", "LOW CV", "COX-2 + PPI"),
    ("HIGH GI risk", "HIGH CV", "Avoid NSAIDs\nif possible"),
]
for i, (gi, cv, rx) in enumerate(matrix):
    yp = 1.82 + i*0.52
    add_rect(s, 8.6, yp, 4.35, 0.5, MED_BLUE if i%2==0 else RGBColor(0x0D,0x2B,0x45))
    add_text(s, f"{gi} / {cv} → {rx}", 8.72, yp+0.04, 4.1, 0.44,
             font_size=11, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)

add_rect(s, 8.6, 4.15, 4.35, 3.2, WHITE)
add_rect(s, 8.6, 4.15, 0.08, 3.2, ORANGE)
add_text(s, "Indications for H. pylori\nTest & Treat with NSAIDs",
         8.75, 4.17, 4.1, 0.65, font_size=13, bold=True, color=DARK_NAVY)
ind = [
    "Test before starting chronic NSAIDs",
    "Prior history of PUD",
    "Dyspepsia on NSAIDs",
    "After NSAID-related GI bleed",
    "Eradicate before initiating therapy",
]
add_multi_bullet(s, ind, 8.75, 4.85, 4.1, 2.4, font_size=12, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 9  – Other Risk Factors
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Additional Risk Factors & Special Causes")

boxes = [
    ("Zollinger–Ellison Syndrome",
     ["Gastrin-secreting tumour (gastrinoma)", "Multiple, atypical ulcers (distal duodenum/jejunum)", "Suspect: H. pylori-neg, NSAID-neg ulcer; diarrhoea; MEN-1",
      "Diagnosis: fasting serum gastrin >1000 pg/mL + secretin stimulation test", "CT/MRI + somatostatin receptor scintigraphy for tumour localisation",
      "Treatment: high-dose PPI; surgical resection if localised"], MED_BLUE),
    ("Cigarette Smoking",
     ["↓ mucosal prostaglandin synthesis", "↑ gastric acid secretion; ↓ duodenal bicarb",
      "↓ mucosal blood flow — impairs healing", "Doubles ulcer risk; ↑ recurrence rate",
      "Delays healing even on PPI/eradication therapy"], DARK_NAVY),
    ("Systemic Diseases",
     ["Alcoholic cirrhosis — ↑ portal hypertension, ↓ hepatic clearance of gastrin",
      "COPD — hypoxia ↓ mucosal blood flow", "Chronic renal failure — ↑ gastrin (↓ renal clearance)",
      "Hyperparathyroidism — hypercalcaemia stimulates gastrin secretion",
      "Stress ulcers: critically ill patients (Cushing — CNS; Curling — burns)"], GREEN),
    ("Genetics & Other",
     ["Blood group O — receptor affinity for H. pylori adhesins", "MEN-1 syndrome — ZES component",
      "Rare: Crohn's disease, viral (CMV, HSV) in immunocompromised",
      "Psychological stress: probably permissive rather than causative",
      "Corticosteroids alone: low risk; synergistic with NSAIDs — high risk"], ORANGE),
]

positions = [(0.4, 1.05), (6.8, 1.05), (0.4, 4.25), (6.8, 4.25)]
for (bx, by), (title, items, col) in zip(positions, boxes):
    add_rect(s, bx, by, 6.0, 0.42, col)
    add_text(s, title, bx+0.1, by+0.03, 5.8, 0.36,
             font_size=14, bold=True, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)
    add_rect(s, bx, by+0.42, 6.0, 2.9, WHITE)
    add_multi_bullet(s, items, bx+0.15, by+0.48, 5.75, 2.8, font_size=12, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 10  – Clinical Presentation
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Clinical Presentation",
             "Symptoms are often indistinguishable between gastric and duodenal ulcers")

add_rect(s, 0.4, 1.05, 8.0, 5.9, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 5.9, MED_BLUE)
add_text(s, "Symptoms & Signs", 0.6, 1.08, 7.7, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
sx = [
    (0, "PAIN (most prominent feature):", True),
    (1, "Epigastric pain — gnawing, burning, or aching in character", False),
    (1, "Radiation to back — suggests penetrating posterior DU (gastroduodenal artery)", False),
    (1, "DU classically: pain 2–3 h post-meal, relieved by food/antacids ('hunger pain')", False),
    (1, "GU classically: pain precipitated by food ('food fear'), weight loss more prominent", False),
    (1, "However: symptoms CANNOT reliably distinguish GU from DU", False),
    (1, "Periodicity: symptoms disappear for weeks/months, then recur (healing/relapse cycle)", False),
    (0, "VOMITING:", True),
    (1, "Not a prominent feature unless gastric outlet obstruction has developed", False),
    (1, "Projectile/bile-free vomiting + succussion splash → GOO", False),
    (0, "OTHER SYMPTOMS:", True),
    (1, "Weight loss: more common in GU (food fear); also in malignancy — biopsy all GU", False),
    (1, "Anaemia: chronic occult bleeding (microcytic, iron-deficiency)", False),
    (1, "Haematemesis / melaena: suggests acute upper GI bleeding", False),
    (0, "EXAMINATION:", True),
    (1, "Epigastric tenderness — mild; percussion tenderness", False),
    (1, "Rigid abdomen + absent bowel sounds → perforation", False),
    (1, "Succussion splash (late GOO)", False),
    (1, "Pallor (anaemia), tachycardia/hypotension (haemorrhage)", False),
]
add_multi_bullet(s, sx, 0.6, 1.55, 7.7, 5.3, font_size=12.5, color=DARK_TEXT)

add_rect(s, 8.7, 1.05, 4.2, 5.9, DARK_NAVY)
add_text(s, "Important Differentials", 8.85, 1.08, 4.0, 0.42,
         font_size=14, bold=True, color=YELLOW_HL)
diffs = [
    "Gastric cancer *",
    "GERD",
    "Functional dyspepsia",
    "Acute pancreatitis",
    "Biliary colic",
    "Gastric volvulus",
    "Ischaemic gut",
    "Aortic aneurysm",
    "Lower lobe pneumonia",
    "",
    "* ALL gastric ulcers must",
    "  have biopsies taken to",
    "  exclude malignancy",
]
y = 1.57
for d in diffs:
    col = YELLOW_HL if d.startswith("*") else WHITE
    add_text(s, d, 8.85, y, 3.9, 0.4,
             font_size=12, color=col, bold=d.startswith("*"))
    y += 0.4

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 11  – Investigations & Diagnosis
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Investigations & Diagnosis",
             "Endoscopy is gold standard · Always biopsy gastric ulcers")

section_box(s, "Upper GI Endoscopy (Gold Standard)", 0.4, 1.05, 8.2, 3.5)
endo = [
    "Visualises mucosal defect directly; allows biopsy, CLO test, therapeutic intervention",
    "GASTRIC ULCERS: ≥6–8 biopsies from ulcer edge (not base) — exclude malignancy",
    "'U' manoeuvre essential: inspect incisura, lesser curve, GOJ",
    "DUODENAL ULCERS: biopsy only if atypical or if malignancy suspected",
    "CLO (Campylobacter-like organism) test: rapid urease test for H. pylori — sensitivity ~90%",
    "Antral biopsy for histology ± Giemsa/modified Giemsa stain for H. pylori",
    "Must confirm healing of ALL gastric ulcers at 6–8 weeks (repeat endoscopy)",
]
add_multi_bullet(s, endo, 0.55, 1.5, 7.9, 2.9, font_size=12.5, color=DARK_TEXT)

section_box(s, "H. pylori Testing Summary", 0.4, 4.65, 8.2, 2.7)
htest = [
    "UBT (Urea Breath Test): BEST for confirming eradication; stop PPI 2 weeks, antibiotics 4 weeks before",
    "Stool Antigen Test (SAT): useful pre- and post-treatment; avoid PPIs 2 weeks before",
    "Serology (IgG): cheap, not affected by PPIs/antibiotics; CANNOT confirm active infection or eradication",
    "False negatives: recent PPI/antibiotics, active GI bleeding → use serology or histology in acute bleed",
]
add_multi_bullet(s, htest, 0.55, 5.1, 7.9, 2.1, font_size=12.5, color=DARK_TEXT)

# Right side
add_rect(s, 8.85, 1.05, 4.05, 6.3, WHITE)
add_rect(s, 8.85, 1.05, 0.08, 6.3, ORANGE)
add_text(s, "Other Investigations", 9.05, 1.08, 3.8, 0.42,
         font_size=14, bold=True, color=DARK_NAVY)
other = [
    "BLOODS:",
    "  FBC — anaemia (iron deficiency)",
    "  U&E — electrolyte disturbance (GOO: hypochloraemic hypokalaemic alkalosis)",
    "  LFTs, coagulation — if bleeding",
    "  Fasting serum gastrin — if ZES suspected (>1000 pg/mL highly suggestive)",
    "  Calcium — rule out hyperparathyroidism",
    "",
    "RADIOLOGY:",
    "  Barium meal: 'niche' sign (GU), clover-leaf deformity (DU); now largely replaced by endoscopy",
    "  CT scan: investigation of choice for suspected perforation (free air / fluid)",
    "  CT/MRI + somatostatin scintigraphy: localise gastrinoma in ZES",
    "  Erect CXR: free air under diaphragm in perforation",
    "",
    "SECRETIN STIMULATION TEST:",
    "  ZES: paradoxical ↑ gastrin after IV secretin",
]
y_off = 1.55
for line in other:
    bld = line.endswith(":") and not line.startswith(" ")
    col = MED_BLUE if bld else DARK_TEXT
    add_text(s, line, 9.05, y_off, 3.7, 0.36,
             font_size=11, bold=bld, color=col)
    y_off += 0.36 if not line == "" else 0.2

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 12  – Endoscopic image slide
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, DARK_NAVY)
slide_header(s, "Endoscopic Appearance — PUD", "Educational imaging",
             bg_color=MED_BLUE, sub_color=WHITE)

add_image(s,
    "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_644f5d01a41988a6473fda233160bb2f0d93f04cd79693ee2f1889ab37d1e08c.jpg",
    0.4, 1.1, 5.9, 4.2)
add_text(s, "Large posterior duodenal bulb ulcer\nActive stage A1 (Sakita-Miwa classification)\nFibrinoid base; surrounding oedematous mucosa",
         0.4, 5.35, 5.9, 1.1, font_size=13, italic=True, color=LIGHT_BLUE,
         align=PP_ALIGN.CENTER)

add_image(s,
    "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_2445e0fa69d758eff88db95e8f9adf6bc96dcc27fd1a0cd2e7b8e264caff293f.jpg",
    6.6, 1.1, 6.3, 4.2)
add_text(s, "Composite panel: H. pylori-associated gastritis & PUD\nNodular gastritis, duodenal and gastric ulcers, erosions",
         6.6, 5.35, 6.3, 1.1, font_size=13, italic=True, color=LIGHT_BLUE,
         align=PP_ALIGN.CENTER)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 13  – Complications: GI Bleeding
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Complications — Upper GI Bleeding",
             "Most common and most lethal complication of PUD")

add_rect(s, 0.4, 1.05, 8.5, 6.35, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 6.35, RED)
add_text(s, "Bleeding Peptic Ulcer", 0.6, 1.08, 8.2, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
bleed = [
    (0, "50% of all UGI bleeds; ~100,000 hospitalisations/year in USA", False),
    (0, "Posterior DU → erodes GASTRODUODENAL ARTERY (GDA) — major vessel bleed", False),
    (0, "3/4 of patients stop bleeding spontaneously with acid suppression + nil by mouth", False),
    (0, "1/4 continue or REBLEED — this group accounts for virtually ALL morbidity/mortality", False),
    (0, "High-risk endoscopic stigmata (Forrest Classification):", True),
    (1, "Ia — Active arterial spurting — 90% rebleed risk", False),
    (1, "Ib — Active oozing — 10–27% rebleed", False),
    (1, "IIa — Non-bleeding visible vessel (NBVV) — 43–55% rebleed risk → TREAT", False),
    (1, "IIb — Adherent clot — 22% rebleed → consider endoscopic removal", False),
    (1, "IIc — Flat pigmented spot — <8% rebleed", False),
    (1, "III — Clean base — <3% rebleed", False),
    (0, "INITIAL MANAGEMENT:", True),
    (1, "Resuscitate: IV access (2 large bore), crystalloids then packed red cells; target Hb 7–9 g/dL", False),
    (1, "IV PPI (bolus + infusion) pre-endoscopy: 80 mg omeprazole → 8 mg/hr (downstages stigmata)", False),
    (1, "Urgent endoscopy within 24 h (high-risk within 12 h after resuscitation)", False),
    (1, "Endoscopic haemostasis: adrenaline injection + second modality (thermal/clips)", False),
    (1, "Post-endoscopy: IV PPI for 72 h → oral PPI; early re-feeding", False),
    (0, "REBLEED / FAILURE:", True),
    (1, "Repeat endoscopy once if rebleeds; thereafter → interventional radiology (embolisation) or surgery", False),
    (1, "Surgery: under-running of ulcer + vagotomy ± pyloroplasty (rare in current era)", False),
]
add_multi_bullet(s, bleed, 0.6, 1.55, 8.3, 5.7, font_size=12, color=DARK_TEXT)

# Right: risk scoring
add_rect(s, 9.15, 1.05, 3.8, 6.35, DARK_NAVY)
add_text(s, "Risk Stratification\nScoring Systems", 9.3, 1.08, 3.5, 0.65,
         font_size=14, bold=True, color=YELLOW_HL, align=PP_ALIGN.CENTER)

add_text(s, "BLATCHFORD SCORE (pre-endoscopy)", 9.3, 1.83, 3.5, 0.42,
         font_size=12, bold=True, color=ORANGE)
bf = [
    "Urea, Hb, SBP, HR",
    "Melaena, syncope",
    "Hepatic/cardiac disease",
    "Score 0 → safe for discharge",
    "Max score = 23",
]
add_multi_bullet(s, bf, 9.3, 2.28, 3.5, 1.5, font_size=11, color=WHITE, bullet_char="• ")

add_text(s, "ROCKALL SCORE (post-endoscopy)", 9.3, 3.88, 3.5, 0.42,
         font_size=12, bold=True, color=ORANGE)
rk = [
    "Age, shock, comorbidity",
    "Endoscopic diagnosis",
    "Stigmata of haemorrhage",
    "Score ≤2 → low risk",
    "Score ≥8 → 41% mortality",
]
add_multi_bullet(s, rk, 9.3, 4.35, 3.5, 1.5, font_size=11, color=WHITE, bullet_char="• ")

add_rect(s, 9.15, 5.95, 3.8, 1.45, RED)
add_text(s, "AIMS65 Score\nAlbumin <3 g/dL, INR >1.5,\nAMS, SBP <90, age >65\n→ predicts in-hospital mortality",
         9.25, 5.98, 3.6, 1.38, font_size=11, color=WHITE)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 14  – Complications: Perforation
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Complications — Perforation",
             "Surgical emergency · Anterior DU most common · Free air on imaging")

add_rect(s, 0.4, 1.05, 8.3, 6.3, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 6.3, ORANGE)
add_text(s, "Perforated Peptic Ulcer", 0.6, 1.08, 8.0, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
perf = [
    (0, "Second most common complication; mortality 10–40% (depends on delay to surgery & comorbidity)", False),
    (0, "ANTERIOR DU: most common perforation site → peritonitis", False),
    (0, "POSTERIOR DU: tends to bleed (GDA erosion); contained perforation → pancreatic penetration", False),
    (0, "GASTRIC perforation: less common; all require biopsy intra-op to exclude malignancy", False),
    (0, "Clinical presentation:", True),
    (1, "Sudden onset SEVERE epigastric pain — 'knife-like'; patient lies still", False),
    (1, "Rigidity → peritonitis: guarding, rebound; 'board-like' abdomen", False),
    (1, "Pain may diminish after a few hours (chemical peritonitis → bacterial → patient may feel 'better')", False),
    (1, "Referred pain to right shoulder (diaphragmatic irritation by free air)", False),
    (1, "Tachycardia, hypotension (late)", False),
    (0, "Investigations:", True),
    (1, "Erect CXR: free air under diaphragm in ~70% of cases", False),
    (1, "CT abdomen (with oral contrast): most sensitive — detects free air, fluid, ulcer location", False),
    (1, "Serum amylase: mildly elevated (ddx pancreatitis — usually >1000 U/L)", False),
    (0, "MANAGEMENT:", True),
    (1, "Resuscitation: IV fluids, NG tube, urinary catheter, IV antibiotics, PPI", False),
    (1, "Surgical repair (primary treatment): laparoscopic or open omental patch (Graham patch)", False),
    (1, "Definitive anti-ulcer procedure only if stable + no peritoneal contamination", False),
    (1, "Conservative (Tayler) management: selected patients — young, small perf, no peritonitis", False),
    (1, "Post-op: test and treat H. pylori; long-term PPI if NSAID/smoking factors remain", False),
]
add_multi_bullet(s, perf, 0.6, 1.55, 8.1, 5.7, font_size=12, color=DARK_TEXT)

# Right panel
add_rect(s, 8.95, 1.05, 4.0, 6.3, DARK_NAVY)
add_text(s, "Mortality Predictors", 9.1, 1.08, 3.75, 0.42,
         font_size=14, bold=True, color=YELLOW_HL)
mort = [
    "Delay to surgery >24 h",
    "Age >70 years",
    "ASA grade ≥3",
    "Active malignancy",
    "Haemodynamic instability",
    "Faecal peritonitis",
    "",
    "Boey Score (0–3):",
    "• Shock (SBP <100)",
    "• Perforation >24 h",
    "• Major medical illness",
    "Score 0: 0% mortality",
    "Score 3: ~100% mortality",
]
y_m = 1.57
for line in mort:
    bld = "Score" in line or "Boey" in line
    col = ORANGE if bld else WHITE
    add_text(s, line, 9.1, y_m, 3.75, 0.4,
             font_size=12, bold=bld, color=col)
    y_m += 0.38 if line else 0.2

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 15  – Complications: Gastric Outlet Obstruction
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Complications — Gastric Outlet Obstruction",
             "Pyloric stenosis · Electrolyte signature · Surgical options")

add_rect(s, 0.4, 1.05, 8.5, 6.3, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 6.3, MED_BLUE)
add_text(s, "Gastric Outlet Obstruction (GOO)", 0.6, 1.08, 8.2, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
goo = [
    (0, "Third complication of PUD; now more commonly due to gastric cancer than PUD", False),
    (0, "Mechanism: fibrotic scarring/oedema at pyloric channel or D1 from chronic/recurrent ulceration", False),
    (0, "Symptoms:", True),
    (1, "Vomiting of undigested food (hours after meal) — bile-free (obstruction pre-papilla)", False),
    (1, "Succussion splash (hand on abdomen + patient rocking)", False),
    (1, "Progressive weight loss, dehydration, satiety", False),
    (0, "Metabolic derangement — CLASSIC PATTERN:", True),
    (1, "Hypochloraemic, hypokalaemic metabolic ALKALOSIS", False),
    (1, "Mechanism: repeated vomiting → loss of H⁺ and Cl⁻ → renal compensation (HCO₃⁻ retention)", False),
    (1, "Paradoxical aciduria: kidneys excrete K⁺ (prioritise Na⁺ reabsorption) + H⁺ despite alkalosis", False),
    (1, "Labs: ↓ Na⁺, ↓ K⁺, ↓ Cl⁻, ↑ HCO₃⁻, ↑ urea (pre-renal); urine pH paradoxically acidic", False),
    (0, "INVESTIGATIONS:", True),
    (1, "Endoscopy: confirms obstruction; biopsies to exclude malignancy (essential!)", False),
    (1, "CT abdomen: gastric dilatation, site of obstruction, wall thickening", False),
    (1, "Saline load test: infuse 750 mL saline; if >400 mL remains at 30 min → obstruction", False),
    (0, "MANAGEMENT:", True),
    (1, "Step 1: NBM + NG tube decompression + IV fluid/electrolyte correction (N. saline + KCl)", False),
    (1, "Step 2: IV PPI, nutritional support", False),
    (1, "Step 3: Endoscopic balloon dilatation (for benign strictures — often requires repeat)", False),
    (1, "Step 4: Surgery if endoscopic dilation fails: truncal vagotomy + gastrojejunostomy or Billroth I/II", False),
]
add_multi_bullet(s, goo, 0.6, 1.55, 8.3, 5.7, font_size=12, color=DARK_TEXT)

add_rect(s, 9.15, 1.05, 3.8, 6.3, DARK_NAVY)
add_text(s, "Electrolyte Abnormality\nin GOO", 9.3, 1.08, 3.5, 0.65,
         font_size=14, bold=True, color=YELLOW_HL, align=PP_ALIGN.CENTER)
elec = [
    "↓ Na⁺ (mild)",
    "↓ K⁺ (hypokalaemia)",
    "↓ Cl⁻ (hypochloraemia)",
    "↑ HCO₃⁻ (alkalosis)",
    "↑ Urea (pre-renal)",
    "Urine: paradoxically ACID",
    "",
    "Treatment:",
    "0.9% NaCl + KCl IV",
    "Replace Cl⁻ and K⁺",
    "Avoid HCO₃⁻",
    "",
    "Differential for GOO:",
    "• Gastric cancer (most common now)",
    "• Chronic PUD",
    "• Pancreatic cancer",
    "• Adult hypertrophic\n  pyloric stenosis",
    "• Crohn's disease",
]
y_e = 1.85
for line in elec:
    bld = line == "Treatment:" or line == "Differential for GOO:"
    col = ORANGE if bld else (YELLOW_HL if line.startswith("↓") or line.startswith("↑") else WHITE)
    add_text(s, line, 9.3, y_e, 3.5, 0.38,
             font_size=11.5, bold=bld, color=col)
    y_e += 0.35 if line else 0.18

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 16  – Medical Management Overview
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Medical Management of PUD",
             "Acid suppression · H. pylori eradication · Mucosal protection")

# Agents table
add_rect(s, 0.4, 1.05, 12.5, 0.42, MED_BLUE)
for hdr, x in [("Drug Class", 0.45), ("Examples", 2.8), ("Mechanism", 5.5), ("Notes", 9.0)]:
    add_text(s, hdr, x, 1.07, 2.3, 0.38,
             font_size=13, bold=True, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)

rows = [
    ("PPIs\n(1st line)", "Omeprazole 20–40 mg\nEsomeprazole, Pantoprazole\nLansoprazole, Rabeprazole",
     "Irreversible block of H⁺/K⁺-ATPase pump\non parietal cell (final common pathway)",
     "90% acid suppression; given 30 min before meals; healing: DU 4 wks, GU 8 wks"),
    ("H2-Receptor\nAntagonists", "Ranitidine (withdrawn),\nFamotidine, Cimetidine",
     "Competitive block of H2 receptors\non parietal cells",
     "Less effective than PPIs; tachyphylaxis; still useful for mild disease"),
    ("Antacids", "Al(OH)₃, Mg(OH)₂, CaCO₃",
     "Neutralise intraluminal acid",
     "Symptomatic relief only; not for healing"),
    ("Sucralfate", "Sucralfate 1 g QID",
     "Coats ulcer base; binds pepsin,\nstimulates prostaglandins",
     "Useful in ZES; avoid in renal failure (Al accumulation)"),
    ("Misoprostol", "Misoprostol 200 mcg QID",
     "PGE1 analogue — stimulates mucus,\nbicarb, mucosal blood flow",
     "GI side effects (diarrhoea); used for NSAID-GI prophylaxis; teratogenic"),
    ("Bismuth\nSalts", "Bismuth subcitrate/subsalicylate",
     "Mucosal protective coating;\nanti-H. pylori bactericidal action",
     "Component of quadruple therapy; darkens stool"),
]

for i, (cls, examp, mech, notes) in enumerate(rows):
    bg = LIGHT_BLUE if i % 2 == 0 else WHITE
    yp = 1.52 + i * 0.82
    add_rect(s, 0.4, yp, 12.5, 0.8, bg)
    add_text(s, cls, 0.45, yp+0.04, 2.3, 0.72, font_size=12, bold=True,
             color=DARK_NAVY, v_anchor=MSO_ANCHOR.MIDDLE)
    add_text(s, examp, 2.8, yp+0.04, 2.65, 0.72, font_size=11,
             color=DARK_TEXT, v_anchor=MSO_ANCHOR.MIDDLE)
    add_text(s, mech, 5.5, yp+0.04, 3.45, 0.72, font_size=11,
             color=DARK_TEXT, v_anchor=MSO_ANCHOR.MIDDLE)
    add_text(s, notes, 9.0, yp+0.04, 3.85, 0.72, font_size=10.5,
             color=DARK_TEXT, v_anchor=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 17  – H. pylori Eradication
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "H. pylori Eradication Therapy",
             "Test-and-treat · Regimens · Resistance · Confirmation of eradication")

# Regimens
add_rect(s, 0.4, 1.05, 12.5, 0.42, DARK_NAVY)
for hdr, x in [("Regimen", 0.45), ("Drugs & Duration", 3.5), ("Eradication Rate", 9.8)]:
    add_text(s, hdr, x, 1.07, 3.3, 0.38, font_size=13, bold=True, color=WHITE)

regimens = [
    ("Standard Triple Therapy\n(1st line, low clarithromycin resistance areas)",
     "PPI (standard dose BD) + Clarithromycin 500 mg BD + Amoxicillin 1 g BD — 7–14 days",
     "~80–85%"),
    ("Bismuth Quadruple\n(1st line where clarithromycin resistance >15%)",
     "PPI BD + Bismuth subcitrate QID + Metronidazole 400 mg QID + Tetracycline 500 mg QID — 10–14 days",
     "~90%"),
    ("Concomitant (Non-Bismuth\nQuadruple) Therapy",
     "PPI BD + Clarithromycin 500 mg BD + Amoxicillin 1 g BD + Metronidazole 400 mg BD — 14 days",
     "~88–90%"),
    ("Sequential Therapy",
     "Days 1–5: PPI + Amoxicillin 1 g BD; Days 6–10: PPI + Clarithromycin + Metronidazole",
     "~85–90%"),
    ("Levofloxacin-based\n(Rescue/2nd line)",
     "PPI BD + Levofloxacin 500 mg OD + Amoxicillin 1 g BD — 10–14 days",
     "~80%"),
    ("Rifabutin-based\n(3rd line / resistant cases)",
     "PPI BD + Amoxicillin 1 g BD + Rifabutin 150 mg BD — 10 days",
     "~70–80%"),
]

for i, (reg, drugs, rate) in enumerate(regimens):
    bg = LIGHT_BLUE if i % 2 == 0 else WHITE
    yp = 1.52 + i * 0.78
    add_rect(s, 0.4, yp, 12.5, 0.76, bg)
    add_text(s, reg, 0.45, yp+0.03, 3.0, 0.7, font_size=11.5, bold=False,
             color=DARK_NAVY, v_anchor=MSO_ANCHOR.MIDDLE)
    add_text(s, drugs, 3.5, yp+0.03, 6.25, 0.7, font_size=11,
             color=DARK_TEXT, v_anchor=MSO_ANCHOR.MIDDLE)
    add_text(s, rate, 9.8, yp+0.03, 2.9, 0.7, font_size=14, bold=True,
             color=GREEN, v_anchor=MSO_ANCHOR.MIDDLE, align=PP_ALIGN.CENTER)

# Bottom notes
add_rect(s, 0.4, 6.25, 12.5, 1.1, DARK_NAVY)
notes_txt = ("CONFIRM ERADICATION: UBT or SAT ≥4 weeks after completing antibiotics and ≥2 weeks after stopping PPI  |  "
             "Antibiotic resistance (especially clarithromycin, metronidazole) is the primary cause of treatment failure  |  "
             "Culture-guided therapy if 2nd-line fails  |  PPI must be continued for full healing course even after eradication (DU 4 wks, GU 8 wks)")
add_text(s, notes_txt, 0.5, 6.28, 12.3, 1.0,
         font_size=11, italic=True, color=LIGHT_BLUE,
         v_anchor=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 18  – Surgical Management
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Surgical Management",
             "Indications · Elective vs emergency · Procedures & post-operative complications")

add_rect(s, 0.4, 1.05, 7.8, 6.3, WHITE)
add_rect(s, 0.4, 1.05, 0.08, 6.3, MED_BLUE)
add_text(s, "Surgery for PUD — Current Role", 0.6, 1.08, 7.5, 0.42,
         font_size=15, bold=True, color=DARK_NAVY)
surg = [
    (0, "ELECTIVE SURGERY: now very rarely indicated (intractable disease not responding to medical Rx)", True),
    (0, "EMERGENCY SURGERY remains essential for:", True),
    (1, "Perforation — omental patch (Graham patch) ± definitive procedure", False),
    (1, "Uncontrolled haemorrhage — failed endoscopy × 2; under-running of ulcer ± vagotomy", False),
    (1, "Gastric outlet obstruction — failed endoscopic dilatation", False),
    (0, "PROCEDURES FOR DU:", True),
    (1, "Truncal vagotomy + pyloroplasty (TV+P): vagotomy to ↓ acid + drainage to avoid gastroparesis", False),
    (1, "Truncal vagotomy + antrectomy (TV+A): most effective; Billroth I or II reconstruction", False),
    (1, "Highly selective vagotomy (HSV/proximal gastric vagotomy): preserves pyloric innervation; lowest side effects; rarely used now", False),
    (0, "POST-OPERATIVE COMPLICATIONS:", True),
    (1, "Dumping syndrome (early): rapid gastric emptying → osmotic shift → vasomotor symptoms 15–30 min post-meal", False),
    (1, "Dumping syndrome (late): hyperglycaemia → insulin surge → reactive hypoglycaemia 1–3 h post-meal", False),
    (1, "Afferent loop syndrome (Billroth II): obstruction → bacterial overgrowth; bilious vomiting", False),
    (1, "Alkaline reflux gastritis: bile reflux → chronic gastritis", False),
    (1, "Post-vagotomy diarrhoea: altered intestinal motility", False),
    (1, "Stomal ulcer: recurrence at gastrojejunal anastomosis", False),
    (1, "Nutritional deficiencies: B12, iron, calcium (especially post-gastrectomy)", False),
    (1, "Gastric remnant cancer: long-term risk after Billroth II (surveillance at 15+ years)", False),
]
add_multi_bullet(s, surg, 0.6, 1.55, 7.6, 5.7, font_size=12, color=DARK_TEXT)

add_rect(s, 8.45, 1.05, 4.5, 6.3, DARK_NAVY)
add_text(s, "Surgical Procedures\n(Visual Guide)", 8.6, 1.08, 4.2, 0.65,
         font_size=14, bold=True, color=YELLOW_HL, align=PP_ALIGN.CENTER)

procs = [
    ("Graham Patch", "Omentum sutured over perforation; simple, quick"),
    ("Billroth I", "Distal gastrectomy; stomach to duodenum (gastroduodenostomy)"),
    ("Billroth II\n(Pólya)", "Distal gastrectomy; stomach to jejunum (loop gastrojejunostomy); duodenal stump closed"),
    ("Roux-en-Y", "Gastrojejunostomy with Roux limb; minimises alkaline reflux"),
    ("HSV", "Denervates parietal cell mass; preserves pylorus; elective only"),
]
y_p = 1.82
for pname, pdesc in procs:
    add_rect(s, 8.45, y_p, 4.5, 0.98, MED_BLUE)
    add_text(s, pname, 8.58, y_p+0.04, 4.2, 0.42, font_size=13, bold=True,
             color=YELLOW_HL, v_anchor=MSO_ANCHOR.MIDDLE)
    add_text(s, pdesc, 8.58, y_p+0.44, 4.2, 0.5, font_size=11, color=WHITE,
             v_anchor=MSO_ANCHOR.MIDDLE)
    y_p += 1.05

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 19  – Special Situations & Follow-up
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, LIGHT_GRAY)
slide_header(s, "Special Situations, Follow-up & Cancer Risk",
             "Refractory ulcers · Pregnancy · Elderly · Surveillance")

boxes2 = [
    ("Refractory Ulcers",
     ["Failure to heal after 8–12 weeks of PPI", "Check compliance; confirm H. pylori eradication (UBT/SAT)",
      "Rule out NSAID/aspirin use; smoking", "Serum gastrin → ZES?; consider IgG4 disease",
      "Biopsy: exclude malignancy; resistance testing (culture)", "Extend/intensify PPI; switch to bismuth quadruple therapy",
      "Rarely: surgery for truly intractable disease"], MED_BLUE),
    ("Elderly Patients",
     ["Higher risk of complications (bleeding, perforation) with fewer symptoms",
      "'Silent ulcer' common — first presentation may be haemorrhage", "NSAIDs + anticoagulants = very high risk",
      "Long-term PPI maintenance often required", "Close monitoring; early endoscopy for any symptom change"], DARK_NAVY),
    ("Pregnancy & PUD",
     ["H. pylori eradication deferred until after delivery", "PPIs: omeprazole/pantoprazole — generally considered safe",
      "Avoid misoprostol (teratogenic/abortifacient)", "Endoscopy: safe after first trimester if absolutely indicated",
      "Manage conservatively where possible"], GREEN),
    ("Follow-up & Cancer Surveillance",
     ["ALL gastric ulcers: repeat OGD at 6–8 weeks to confirm healing and re-biopsy",
      "Failure to heal → early endoscopic follow-up → exclude malignancy", "H. pylori eradication: ↓ gastric cancer risk (strongest modifiable risk factor)",
      "Post-gastrectomy: endoscopic surveillance starting 15 years post-op (Billroth II especially)",
      "MALT lymphoma: follow-up after H. pylori eradication for regression"], ORANGE),
]

pos2 = [(0.4, 1.05), (6.8, 1.05), (0.4, 4.3), (6.8, 4.3)]
for (bx, by), (title, items, col) in zip(pos2, boxes2):
    add_rect(s, bx, by, 6.0, 0.42, col)
    add_text(s, title, bx+0.1, by+0.03, 5.8, 0.36,
             font_size=14, bold=True, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)
    add_rect(s, bx, by+0.42, 6.0, 2.82, WHITE)
    add_multi_bullet(s, items, bx+0.15, by+0.48, 5.75, 2.72, font_size=12, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════════════════════════
# SLIDE 20  – Summary / Key Take-Home Messages
# ═══════════════════════════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank_layout)
add_rect(s, 0, 0, 13.333, 7.5, DARK_NAVY)
add_rect(s, 0, 0, 13.333, 1.05, MED_BLUE)
add_text(s, "Key Take-Home Messages", 0.3, 0.08, 12.8, 0.9,
         font_size=30, bold=True, color=WHITE, v_anchor=MSO_ANCHOR.MIDDLE)

msgs = [
    ("1", "H. pylori and NSAIDs cause >90% of PUD. Always determine the aetiology — it drives management."),
    ("2", "No acid, no ulcer — but eradicating H. pylori transforms PUD from a chronic relapsing to a curable disease."),
    ("3", "ALL gastric ulcers must be biopsied and endoscopically confirmed healed at 6–8 weeks — malignancy must be excluded."),
    ("4", "Forrest IIa (visible vessel) carries ~50% rebleed risk — mandates endoscopic haemostasis; Forrest III (clean base) is safe for early discharge."),
    ("5", "GOO produces the classic hypochloraemic, hypokalaemic metabolic alkalosis — restore Cl⁻ and K⁺ before surgery."),
    ("6", "Eradication confirmation (UBT/SAT) must be performed ≥4 weeks post-antibiotics and ≥2 weeks off PPI."),
    ("7", "Perforated DU: anterior → peritonitis; posterior → bleeds GDA. Boey score predicts surgical mortality."),
    ("8", "Surgery is now almost exclusively for emergency complications — the era of elective acid-reducing surgery is over."),
]

for i, (num, msg) in enumerate(msgs):
    yp = 1.15 + i * 0.76
    add_rect(s, 0.4, yp, 0.55, 0.62, ORANGE)
    add_text(s, num, 0.4, yp+0.03, 0.55, 0.56, font_size=22, bold=True,
             color=WHITE, align=PP_ALIGN.CENTER, v_anchor=MSO_ANCHOR.MIDDLE)
    add_rect(s, 0.98, yp, 11.95, 0.62, RGBColor(0x14, 0x38, 0x5A))
    add_text(s, msg, 1.1, yp+0.03, 11.7, 0.56, font_size=14, color=WHITE,
             v_anchor=MSO_ANCHOR.MIDDLE)

add_text(s, "Sources: Schwartz's Principles of Surgery 11e · Sleisenger & Fordtran's GI & Liver Disease 11e\n"
            "Bailey & Love's Short Practice of Surgery 28e · Robbins & Kumar Basic Pathology · Yamada's Textbook of Gastroenterology 7e",
         0.4, 7.1, 12.5, 0.35, font_size=10, italic=True, color=LIGHT_BLUE,
         align=PP_ALIGN.CENTER)

# ─────────────────────────────────────────────────────────────────
out_path = "/tmp/workspace/pud-presentation/Peptic_Ulcer_Disease_PG.pptx"
prs.save(out_path)
print(f"Saved: {out_path}")
print(f"Slides: {len(prs.slides)}")
Running Command

cd /tmp/workspace/pud-presentation && python build_pud.py 2>&1

Running Command

cd /tmp/workspace/pud-presentation # Download images using curl curl -s -L "https://cdn.orris.care/cdss_images/Pathology_1760047119073_99ab0840-08f9-4a89-92d7-23c5c6144c82.jpg" -o img_hpylori.jpg && echo "img1 ok" curl -s -L "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_644f5d01a41988a6473fda233160bb2f0d93f04cd79693ee2f1889ab37d1e08c.jpg" -o img_endo1.jpg && echo "img2 ok" curl -s -L "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_2445e0fa69d758eff88db95e8f9adf6bc96dcc27fd1a0cd2e7b8e264caff293f.jpg" -o img_endo2.jpg && echo "img3 ok" ls -lh *.jpg

Running Command

cd /tmp/workspace/pud-presentation python3 - <<'EOF' from pptx import Presentation from pptx.util import Inches, Pt from pptx.dml.color import RGBColor from pptx.enum.text import PP_ALIGN, MSO_ANCHOR prs = Presentation("Peptic_Ulcer_Disease_PG.pptx") # Slide index 6 (0-based) = slide 7 (H. pylori) — add image to slide 6 # Slide index 11 (0-based) = slide 12 (endoscopic images) # Slide 7 (index 6): H. pylori histology image s7 = prs.slides[6] try: pic = s7.shapes.add_picture( "/tmp/workspace/pud-presentation/img_hpylori.jpg", Inches(8.45), Inches(1.05), width=Inches(4.5), height=Inches(3.0) ) print("Slide 7 image added OK") except Exception as e: print(f"Slide 7 image error: {e}") # Slide 12 (index 11): endoscopic images (both) s12 = prs.slides[11] try: pic1 = s12.shapes.add_picture( "/tmp/workspace/pud-presentation/img_endo1.jpg", Inches(0.4), Inches(1.1), width=Inches(5.9), height=Inches(4.2) ) print("Slide 12 img1 added OK") except Exception as e: print(f"Slide 12 img1 error: {e}") try: pic2 = s12.shapes.add_picture( "/tmp/workspace/pud-presentation/img_endo2.jpg", Inches(6.6), Inches(1.1), width=Inches(6.3), height=Inches(4.2) ) print("Slide 12 img2 added OK") except Exception as e: print(f"Slide 12 img2 error: {e}") prs.save("Peptic_Ulcer_Disease_PG.pptx") print(f"Saved with images. Total slides: {len(prs.slides)}") EOF

Running Command

cd /tmp/workspace/pud-presentation # Convert WEBP to JPEG using Pillow python3 -c " from PIL import Image img = Image.open('img_hpylori.jpg').convert('RGB') img.save('img_hpylori_conv.jpg', 'JPEG') print('Converted OK') " python3 - <<'EOF' from pptx import Presentation from pptx.util import Inches, Pt prs = Presentation("Peptic_Ulcer_Disease_PG.pptx") s7 = prs.slides[6] try: pic = s7.shapes.add_picture( "/tmp/workspace/pud-presentation/img_hpylori_conv.jpg", Inches(8.45), Inches(1.05), width=Inches(4.5), height=Inches(3.0) ) print("Slide 7 image added OK") except Exception as e: print(f"Slide 7 image error: {e}") prs.save("Peptic_Ulcer_Disease_PG.pptx") print("Final save OK") EOF

Running Command

ls -lh /tmp/workspace/pud-presentation/Peptic_Ulcer_Disease_PG.pptx

Your presentation is ready:

Peptic Ulcer Disease PG

Presentation · PPTX


What's Inside — 20 Slides

#Slide Title
1Title slide — Department of Internal Medicine branding
2Lecture Outline — 16-topic index
3Definition & Historical Background — Schwartz/Nobel milestones
4Epidemiology & Burden — stat callout boxes (90% DU / H. pylori, etc.)
5Anatomy & Common Sites — Johnson classification of gastric ulcers
6Pathophysiology — Aggressive vs defensive forces balance diagram + acid secretion physiology
7H. pylori — Primary Causative Agent — virulence factors (CagA, VacA), DU mechanism, testing methods — with histology image
8NSAIDs & Aspirin — dual mechanism, risk matrix, MUCOSA/VIGOR trial data
9Other Risk Factors — ZES, smoking, systemic diseases, genetics
10Clinical Presentation — symptoms, DU vs GU patterns, differential diagnoses
11Investigations & Diagnosis — endoscopy, H. pylori testing, radiology, serum gastrin
12Endoscopic Image Gallery — real clinical endoscopy photos embedded
13Complications: GI Bleeding — Forrest classification, Blatchford/Rockall/AIMS65 scoring, management algorithm
14Complications: Perforation — Boey score, Graham patch, conservative management
15Complications: Gastric Outlet Obstruction — classic electrolyte pattern, surgical options
16Medical Management — drug class table (PPIs, H2RAs, sucralfate, misoprostol, bismuth)
17H. pylori Eradication Regimens — 6 regimens with eradication rates, confirmation protocols
18Surgical Management — Billroth I/II, vagotomy types, post-op complications
19Special Situations — refractory ulcers, elderly, pregnancy, cancer surveillance
208 Key Take-Home Messages
Sources used: Schwartz's Principles of Surgery 11e, Sleisenger & Fordtran's GI & Liver Disease, Bailey & Love's Short Practice of Surgery 28e, Robbins & Kumar Basic Pathology, Yamada's Textbook of Gastroenterology 7e.

powerpoint presentation for postgraduate internal medicine on ITP make it as detailed as possible with light theme

Finding Sources
Finding Sources
Searching Images

ITP immune thrombocytopenia purpura petechiae bleeding

This composite clinical photograph illustrates multisite cutaneous and mucosal manifestations of drug-induced immune thrombocytopenic purpura (ITP). The left panel shows the lower extremities with a diffuse, symmetric distribution of pinpoint, non-blanching red-to-purple petechiae and larger, confluent purpuric macules. The center panel displays a close-up of the axillary region, highlighting a prominent, deep-purple ecchymosis alongside scattered petechiae, indicative of significant dermal hemorrhage. The right panel demonstrates mucosal involvement with 'wet purpura'—specifically, dark, hemorrhagic bullae and macules located on the buccal mucosa and inner lip. These findings collectively characterize a systemic bleeding diathesis, clinically relevant for identifying severe thrombocytopenia (platelet counts typically <10,000/uL) and assessing the risk of internal hemorrhage in a dermatology or hematology context.

This composite clinical photograph illustrates multisite cutaneous and mucosal manifestations of drug-induced immune thrombocytopenic purpura (ITP). The left panel shows the lower extremities with a diffuse, symmetric distribution of pinpoint, non-blanching red-to-purple petechiae and larger, confluent purpuric macules. The center panel displays a close-up of the axillary region, highlighting a prominent, deep-purple ecchymosis alongside scattered petechiae, indicative of significant dermal hemorrhage. The right panel demonstrates mucosal involvement with 'wet purpura'—specifically, dark, hemorrhagic bullae and macules located on the buccal mucosa and inner lip. These findings collectively characterize a systemic bleeding diathesis, clinically relevant for identifying severe thrombocytopenia (platelet counts typically <10,000/uL) and assessing the risk of internal hemorrhage in a dermatology or hematology context.

Clinical photograph of the bilateral lower extremities of an elderly male, demonstrating widespread cutaneous manifestations of a bleeding disorder. The image shows the anterior (pretibial) regions of both legs, featuring a dense distribution of non-blanching, pinpoint-sized reddish-purple spots consistent with petechiae. The lesions are multifocal and symmetric in their distribution across both shins. Two black arrows point toward the primary clusters of these hemorrhagic lesions. There is evidence of mild underlying erythema and possible trace edema in the affected skin. The visual presentation is highly characteristic of severe thrombocytopenia or small-vessel vasculitis, frequently associated with immune-mediated conditions such as Immune Thrombocytopenic Purpura (ITP) following triggers like recent viral vaccination. The patient's clothing (trousers and socks) is retracted to reveal the distal leg pathology, emphasizing the clinical importance of physical examination in detecting systemic hemostatic failure.

Clinical photograph of the bilateral lower extremities of an elderly male, demonstrating widespread cutaneous manifestations of a bleeding disorder. The image shows the anterior (pretibial) regions of both legs, featuring a dense distribution of non-blanching, pinpoint-sized reddish-purple spots consistent with petechiae. The lesions are multifocal and symmetric in their distribution across both shins. Two black arrows point toward the primary clusters of these hemorrhagic lesions. There is evidence of mild underlying erythema and possible trace edema in the affected skin. The visual presentation is highly characteristic of severe thrombocytopenia or small-vessel vasculitis, frequently associated with immune-mediated conditions such as Immune Thrombocytopenic Purpura (ITP) following triggers like recent viral vaccination. The patient's clothing (trousers and socks) is retracted to reveal the distal leg pathology, emphasizing the clinical importance of physical examination in detecting systemic hemostatic failure.

Reading File
Reading File
Reading File
Reading File
Reading File
Finding Sources
Searching Images

peripheral blood smear thrombocytopenia large platelets

Reading File
Finding Sources
Searching Images

splenomegaly spleen ITP immune destruction platelets

This histopathology image shows splenic red pulp from a patient with immune thrombocytopenia (ITP). Acquired anti-platelet IgG produced largely by the spleen mediates platelet opsonization and clearance, reflected here by aggregates of foamy histiocytes within the red pulp. The foamy appearance results from accumulation of phospholipids within phagocytosed platelets, producing lipid-laden macrophages. In addition, the specimen reveals expansion of splenic white pulp with formation of secondary lymphoid follicles and dilation of sinuses, consistent with a splenic immune/adaptive response. Mild myeloid metaplasia, a known compensatory change, may accompany chronic sequestration of hematopoietic elements. The overall architecture demonstrates prominent macrophagic activity and altered splenic microenvironments that accompany thrombocytopenia. Hematoxylin and eosin staining highlights numerous vacuolated cytoplasmic inclusions in histiocytes and a background of scattered lymphocytes and erythrocytes. Notably, the image emphasizes the pathophysiology of ITP: senescence/ destruction of antibody-coated platelets in the reticuloendothelial system, particularly within the spleen. Clinically, these changes correlate with reduced platelet counts, mucocutaneous bleeding risk, and potential responsiveness to splenectomy. This image is valuable for education on splenic involvement in ITP, macrophage biology, and differential diagnosis with other causes of splenomegaly. The image is suitable for pathology teaching, case review, and research on splenic macrophage dynamics in ITP.

This histopathology image shows splenic red pulp from a patient with immune thrombocytopenia (ITP). Acquired anti-platelet IgG produced largely by the spleen mediates platelet opsonization and clearance, reflected here by aggregates of foamy histiocytes within the red pulp. The foamy appearance results from accumulation of phospholipids within phagocytosed platelets, producing lipid-laden macrophages. In addition, the specimen reveals expansion of splenic white pulp with formation of secondary lymphoid follicles and dilation of sinuses, consistent with a splenic immune/adaptive response. Mild myeloid metaplasia, a known compensatory change, may accompany chronic sequestration of hematopoietic elements. The overall architecture demonstrates prominent macrophagic activity and altered splenic microenvironments that accompany thrombocytopenia. Hematoxylin and eosin staining highlights numerous vacuolated cytoplasmic inclusions in histiocytes and a background of scattered lymphocytes and erythrocytes. Notably, the image emphasizes the pathophysiology of ITP: senescence/ destruction of antibody-coated platelets in the reticuloendothelial system, particularly within the spleen. Clinically, these changes correlate with reduced platelet counts, mucocutaneous bleeding risk, and potential responsiveness to splenectomy. This image is valuable for education on splenic involvement in ITP, macrophage biology, and differential diagnosis with other causes of splenomegaly. The image is suitable for pathology teaching, case review, and research on splenic macrophage dynamics in ITP.

Reading File
Reading File
Reading File
Running Command

mkdir -p /tmp/workspace/itp-presentation && ls /tmp/workspace/

Writing File

~/itp-presentation/build_itp.py

from pptx import Presentation
from pptx.util import Inches, Pt, Emu
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR

# ─── LIGHT THEME PALETTE ───────────────────────────────────────────
WHITE       = RGBColor(0xFF, 0xFF, 0xFF)
OFF_WHITE   = RGBColor(0xF7, 0xF9, 0xFC)
LIGHT_GRAY  = RGBColor(0xEE, 0xF2, 0xF7)
MID_GRAY    = RGBColor(0xD0, 0xD8, 0xE4)
DARK_TEXT   = RGBColor(0x1A, 0x1A, 0x2E)
MED_TEXT    = RGBColor(0x3D, 0x3D, 0x5C)

# Accent colours (vivid but clean on white)
DEEP_TEAL   = RGBColor(0x0B, 0x6E, 0x7C)   # headers / section titles
TEAL_LIGHT  = RGBColor(0xD6, 0xF0, 0xF3)   # content backgrounds
MED_TEAL    = RGBColor(0x1A, 0x9A, 0xAB)   # subheaders
CRIMSON     = RGBColor(0xC0, 0x30, 0x30)   # danger / alerts
CRIMSON_LIGHT = RGBColor(0xFD, 0xEC, 0xEC)
AMBER       = RGBColor(0xD9, 0x7B, 0x0A)   # caution
AMBER_LIGHT = RGBColor(0xFE, 0xF3, 0xD7)
PURPLE      = RGBColor(0x5E, 0x35, 0x9E)   # pharmacology
PURPLE_LIGHT= RGBColor(0xEF, 0xE8, 0xFB)
GREEN       = RGBColor(0x1A, 0x7C, 0x45)
GREEN_LIGHT = RGBColor(0xE4, 0xF7, 0xEC)
BLUE        = RGBColor(0x1A, 0x56, 0xAB)
BLUE_LIGHT  = RGBColor(0xE4, 0xEE, 0xFB)

prs = Presentation()
prs.slide_width  = Inches(13.333)
prs.slide_height = Inches(7.5)
blank = prs.slide_layouts[6]

# ─── UTILITIES ─────────────────────────────────────────────────────
def rect(slide, x, y, w, h, fill, line=False):
    sh = slide.shapes.add_shape(1, Inches(x), Inches(y), Inches(w), Inches(h))
    sh.fill.solid(); sh.fill.fore_color.rgb = fill
    if line:
        sh.line.color.rgb = MID_GRAY; sh.line.width = Pt(0.5)
    else:
        sh.line.fill.background()
    return sh

def txt(slide, text, x, y, w, h,
        sz=14, bold=False, italic=False, color=DARK_TEXT,
        align=PP_ALIGN.LEFT, va=MSO_ANCHOR.TOP, wrap=True, name="Calibri"):
    tb = slide.shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
    tf = tb.text_frame; tf.word_wrap = wrap; tf.vertical_anchor = va
    tf.margin_left = tf.margin_right = Inches(0.04)
    tf.margin_top  = tf.margin_bottom = Inches(0.02)
    p = tf.paragraphs[0]; p.alignment = align
    r = p.add_run(); r.text = text
    r.font.name = name; r.font.size = Pt(sz)
    r.font.bold = bold; r.font.italic = italic; r.font.color.rgb = color
    return tb

def bullets(slide, items, x, y, w, h, sz=13, color=DARK_TEXT, bullet="▸ "):
    """items: list of str, or (level, text, bold) tuples"""
    tb = slide.shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
    tf = tb.text_frame; tf.word_wrap = True; tf.vertical_anchor = MSO_ANCHOR.TOP
    tf.margin_left = Inches(0.08); tf.margin_right = Inches(0.05)
    tf.margin_top  = Inches(0.04); tf.margin_bottom = Inches(0.04)
    first = True
    for item in items:
        lvl, text, bold = (item if not isinstance(item, str) else (0, item, False))
        p = tf.paragraphs[0] if first else tf.add_paragraph()
        first = False
        p.space_before = Pt(1); p.space_after = Pt(1)
        r = p.add_run()
        r.text = "    " * lvl + bullet + text
        r.font.name = "Calibri"; r.font.size = Pt(sz)
        r.font.bold = bold; r.font.color.rgb = color
    return tb

def header_bar(slide, title, subtitle=None, accent=DEEP_TEAL):
    """Crisp top bar on white slide"""
    bh = 1.0
    rect(slide, 0, 0, 13.333, bh, accent)
    txt(slide, title, 0.28, 0.08, 12.5, 0.6,
        sz=30, bold=True, color=WHITE, va=MSO_ANCHOR.MIDDLE)
    if subtitle:
        txt(slide, subtitle, 0.28, 0.65, 12.5, 0.32,
            sz=13, italic=True, color=RGBColor(0xCC, 0xEE, 0xF2))
    # thin accent line below bar
    rect(slide, 0, bh, 13.333, 0.06, MED_TEAL)

def section_card(slide, title, x, y, w, h, accent=DEEP_TEAL, bg=TEAL_LIGHT):
    rect(slide, x, y, w, 0.38, accent)
    txt(slide, title, x+0.1, y+0.03, w-0.2, 0.32,
        sz=13, bold=True, color=WHITE, va=MSO_ANCHOR.MIDDLE)
    rect(slide, x, y+0.38, w, h-0.38, bg, line=True)

def kpi_box(slide, number, label, x, y, w, h, accent=DEEP_TEAL, bg=TEAL_LIGHT):
    rect(slide, x, y, w, h, bg, line=True)
    rect(slide, x, y, w, 0.06, accent)
    txt(slide, number, x, y+0.1, w, h*0.52,
        sz=30, bold=True, color=accent, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)
    txt(slide, label, x, y+h*0.55, w, h*0.42,
        sz=11, color=MED_TEXT, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════
# SLIDE 1 — Title
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
rect(s, 0, 0, 13.333, 3.6, DEEP_TEAL)
# diagonal accent
rect(s, 0, 3.52, 13.333, 0.16, MED_TEAL)
rect(s, 0, 3.68, 13.333, 0.06, AMBER)

txt(s, "IMMUNE THROMBOCYTOPENIA", 0.8, 0.7, 11.8, 1.5,
    sz=46, bold=True, color=WHITE, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)
txt(s, "(ITP)", 0.8, 2.0, 11.8, 0.65,
    sz=28, bold=True, color=RGBColor(0xA0, 0xE0, 0xE8), align=PP_ALIGN.CENTER)
txt(s, "A Comprehensive Postgraduate Review  |  Department of Internal Medicine",
    0.8, 2.75, 11.8, 0.55, sz=16, italic=True,
    color=RGBColor(0xCC, 0xEE, 0xF2), align=PP_ALIGN.CENTER)

txt(s, "Formerly: Idiopathic Thrombocytopenic Purpura", 1.5, 3.95, 10.3, 0.55,
    sz=17, italic=True, color=MED_TEXT, align=PP_ALIGN.CENTER)
txt(s, "Sources: Harrison's Principles of Internal Medicine 22e (2025) · Goldman-Cecil Medicine · Washington Manual of Medical Therapeutics\n"
       "Rosen's Emergency Medicine · Sabiston Textbook of Surgery · Fischer's Mastery of Surgery",
    0.8, 6.85, 11.8, 0.55, sz=10.5, italic=True,
    color=MED_TEXT, align=PP_ALIGN.CENTER)

# ═══════════════════════════════════════════════════════════
# SLIDE 2 — Outline
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Lecture Outline", "What we will cover today")

topics_L = [
    "1.  Definition & Terminology",
    "2.  Epidemiology",
    "3.  Classification (Primary vs Secondary)",
    "4.  Pathophysiology",
    "5.  Clinical Presentation",
    "6.  Approach to Diagnosis",
    "7.  Differential Diagnosis",
    "8.  Investigations",
]
topics_R = [
    "9.  ASH 2019 Guidelines — Disease Phases",
    "10. Treatment — First-line",
    "11. Treatment — Second-line (Rituximab / TPO-RA)",
    "12. Treatment — Splenectomy",
    "13. Emergency Management (Severe/Life-threatening)",
    "14. ITP in Special Populations",
    "15. Monitoring & Follow-up",
    "16. Key Take-Home Messages",
]
rect(s, 0.5, 1.15, 5.9, len(topics_L)*0.5+0.2, TEAL_LIGHT, line=True)
rect(s, 0.5, 1.15, 0.06, len(topics_L)*0.5+0.2, DEEP_TEAL)
for i, t in enumerate(topics_L):
    txt(s, t, 0.65, 1.22+i*0.5, 5.65, 0.47, sz=14.5, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)

rect(s, 6.95, 1.15, 5.9, len(topics_R)*0.5+0.2, TEAL_LIGHT, line=True)
rect(s, 6.95, 1.15, 0.06, len(topics_R)*0.5+0.2, MED_TEAL)
for i, t in enumerate(topics_R):
    txt(s, t, 7.1, 1.22+i*0.5, 5.65, 0.47, sz=14.5, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════
# SLIDE 3 — Definition & Terminology
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Definition & Terminology")

rect(s, 0.45, 1.12, 12.4, 1.8, TEAL_LIGHT, line=True)
rect(s, 0.45, 1.12, 0.07, 1.8, DEEP_TEAL)
txt(s, "Definition", 0.62, 1.14, 11.8, 0.42, sz=14, bold=True, color=DEEP_TEAL)
txt(s, "Immune Thrombocytopenia (ITP) is an acquired autoimmune disorder characterised by isolated thrombocytopenia "
       "(platelet count <100 × 10⁹/L) in the absence of an identifiable underlying cause. It results from immune-mediated "
       "platelet destruction AND inhibition of platelet release from megakaryocytes — making it a disorder of both "
       "decreased platelet survival and impaired production.",
    0.62, 1.58, 11.8, 1.28, sz=14.5, color=DARK_TEXT, wrap=True)

rect(s, 0.45, 3.05, 5.9, 4.3, OFF_WHITE, line=True)
rect(s, 0.45, 3.05, 0.07, 4.3, AMBER)
txt(s, "Terminology Evolution", 0.62, 3.08, 5.6, 0.4, sz=13, bold=True, color=AMBER)
term_items = [
    "\"Idiopathic\" → \"Immune\" (cause now understood)",
    "\"Purpura\" removed from name (not always present)",
    "Current preferred term: Immune Thrombocytopenia (ITP)",
    "ASH 2019 & IWG (International Working Group) consensus terminology",
    "Threshold changed: platelet <100 × 10⁹/L (previously <150 × 10⁹/L)",
    "Rationale: counts 100–150 × 10⁹/L usually benign; ~10% develop true ITP over 10 years",
]
bullets(s, term_items, 0.62, 3.52, 5.68, 3.7, sz=13)

rect(s, 6.65, 3.05, 6.2, 4.3, OFF_WHITE, line=True)
rect(s, 6.65, 3.05, 0.07, 4.3, MED_TEAL)
txt(s, "ITP Disease Phases (IWG 2010 / ASH 2019)", 6.82, 3.08, 5.9, 0.4, sz=13, bold=True, color=MED_TEAL)

phases = [
    ("Newly Diagnosed", "0–3 months from diagnosis", TEAL_LIGHT, DEEP_TEAL),
    ("Persistent", "3–12 months; failed to achieve CR or SR spontaneously or after stopping treatment", AMBER_LIGHT, AMBER),
    ("Chronic", ">12 months duration; not in spontaneous or treatment-maintained remission", CRIMSON_LIGHT, CRIMSON),
    ("Severe ITP", "Platelet <20 × 10⁹/L with bleeding requiring treatment", PURPLE_LIGHT, PURPLE),
    ("Refractory", "Failure to respond or relapsed after splenectomy", BLUE_LIGHT, BLUE),
]
yp = 3.55
for name, desc, bg, accent in phases:
    rect(s, 6.65, yp, 6.2, 0.72, bg, line=True)
    rect(s, 6.65, yp, 0.07, 0.72, accent)
    txt(s, name, 6.82, yp+0.04, 2.4, 0.64, sz=12.5, bold=True, color=accent, va=MSO_ANCHOR.MIDDLE)
    txt(s, desc, 9.3, yp+0.04, 3.4, 0.64, sz=11.5, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)
    yp += 0.76

# ═══════════════════════════════════════════════════════════
# SLIDE 4 — Epidemiology
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Epidemiology")

# KPI boxes
kpi_data = [
    ("5–10", "per 100,000\nadults/year\n(incidence)"),
    ("9.5", "per 100,000\n(children/year)"),
    ("3:1", "Female:Male\nratio (adults)"),
    ("~80%", "Children: spontaneous\nremission rate"),
    ("30–40%", "Adults who relapse\nafter 1st-line therapy"),
    ("~60%", "Long-term remission\nafter splenectomy"),
]
kpi_accs = [DEEP_TEAL, MED_TEAL, BLUE, GREEN, AMBER, PURPLE]
kpi_bgs  = [TEAL_LIGHT, TEAL_LIGHT, BLUE_LIGHT, GREEN_LIGHT, AMBER_LIGHT, PURPLE_LIGHT]
for i, ((num, lbl), acc, bg) in enumerate(zip(kpi_data, kpi_accs, kpi_bgs)):
    col, row = i % 3, i // 3
    kpi_box(s, num, lbl, 0.5 + col*4.27, 1.15 + row*1.85, 3.9, 1.65, acc, bg)

# Bottom section
rect(s, 0.5, 4.95, 12.4, 2.4, WHITE, line=True)
rect(s, 0.5, 4.95, 0.07, 2.4, DEEP_TEAL)
txt(s, "Key Epidemiological Facts", 0.67, 4.98, 11.7, 0.4, sz=13, bold=True, color=DEEP_TEAL)
epi_facts = [
    (0, "BIMODAL age distribution: children 1–5 years old (acute, post-viral) AND adults >60 years (chronic, insidious)", False),
    (0, "Children: male = female; mainly acute post-infectious; >90% self-limited remission within weeks", False),
    (0, "Adults: female predominance (F:M = 3:1); chronic course; rare spontaneous remission", False),
    (0, "Geographic variation in H. pylori association — relevant in regions with high H. pylori prevalence", False),
    (0, "Secondary ITP accounts for ~20% of all cases; SLE and HIV are most common underlying conditions", False),
]
bullets(s, epi_facts, 0.67, 5.42, 12.1, 1.85, sz=13)

# ═══════════════════════════════════════════════════════════
# SLIDE 5 — Classification
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Classification — Primary vs Secondary ITP",
           "Diagnosis of exclusion — secondary causes must be actively excluded")

# Primary
section_card(s, "PRIMARY ITP", 0.45, 1.12, 6.0, 2.85, DEEP_TEAL, TEAL_LIGHT)
primary = [
    "No identifiable underlying cause or precipitant",
    "Diagnosis of exclusion — secondary causes ruled out",
    "Accounts for ~80% of all ITP cases",
    "Pathophysiology: autoantibodies (mainly IgG anti-GPIIb/IIIa) → platelet opsonisation → splenic destruction",
    "Also: T-cell mediated cytotoxicity; impaired megakaryopoiesis",
]
bullets(s, primary, 0.55, 1.55, 5.8, 2.3, sz=12.5)

# Secondary
section_card(s, "SECONDARY ITP", 6.8, 1.12, 6.1, 2.85, CRIMSON, CRIMSON_LIGHT)
secondary = [
    "Accounts for ~20% of ITP cases",
    "Treatment must address underlying cause first",
]
bullets(s, secondary, 6.9, 1.55, 5.9, 0.75, sz=12.5, color=DARK_TEXT)

sec_causes = [
    ("Autoimmune", "SLE, RA, antiphospholipid syndrome, Evans' syndrome", TEAL_LIGHT, DEEP_TEAL),
    ("Infections", "HIV, HCV, HBV, EBV (infectious mono), H. pylori, CMV, varicella, rubella", AMBER_LIGHT, AMBER),
    ("Haematological", "CLL, NHL, Hodgkin lymphoma, myelodysplastic syndromes", PURPLE_LIGHT, PURPLE),
    ("Drugs", "Heparin (HIT), quinidine, quinine, sulfonamides, vancomycin, β-lactams, GPIIb/IIIa inhibitors", CRIMSON_LIGHT, CRIMSON),
    ("Other", "Post-vaccine (rare), post-transfusion purpura, pregnancy-related", BLUE_LIGHT, BLUE),
]
yp = 2.36
for name, desc, bg, accent in sec_causes:
    rect(s, 6.8, yp, 6.1, 0.55, bg, line=True)
    rect(s, 6.8, yp, 0.06, 0.55, accent)
    txt(s, name, 6.9, yp+0.04, 1.7, 0.47, sz=11.5, bold=True, color=accent, va=MSO_ANCHOR.MIDDLE)
    txt(s, desc, 8.65, yp+0.04, 4.1, 0.47, sz=11, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)
    yp += 0.58

# Bottom: Drug-induced note
rect(s, 0.45, 4.05, 12.45, 1.5, AMBER_LIGHT, line=True)
rect(s, 0.45, 4.05, 0.07, 1.5, AMBER)
txt(s, "Drug-Induced ITP (DITP) — Important Distinction", 0.62, 4.08, 12.0, 0.4,
    sz=13, bold=True, color=AMBER)
txt(s, "DITP is caused by drug-dependent platelet antibodies — distinct from direct bone marrow suppression. "
       "Diagnosis: thrombocytopenia improves with drug cessation, recurs on rechallenge. "
       "Common agents: heparin (HIT — see separate pathway), quinine/quinidine (strongest evidence), "
       "sulfonamides, vancomycin, procainamide, gold salts, GPIIb/IIIa inhibitors.",
    0.62, 4.52, 12.1, 0.95, sz=13, color=DARK_TEXT)

# Pseudothrombocytopenia note
rect(s, 0.45, 5.65, 12.45, 1.7, LIGHT_GRAY, line=True)
rect(s, 0.45, 5.65, 0.07, 1.7, MID_GRAY)
txt(s, "⚠ Pseudothrombocytopenia — ALWAYS EXCLUDE FIRST", 0.62, 5.68, 12.0, 0.42,
    sz=13, bold=True, color=DARK_TEXT)
pseudo = [
    "EDTA-dependent platelet agglutination — most common cause of artefactual low platelet count",
    "Check: peripheral blood smear (platelet clumps); repeat count in citrate or heparin tube",
    "Giant platelets (e.g. MYH9 mutations, Bernard-Soulier) miscounted as WBCs by automated analysers",
]
bullets(s, pseudo, 0.62, 6.14, 12.1, 1.12, sz=12.5)

# ═══════════════════════════════════════════════════════════
# SLIDE 6 — Pathophysiology
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Pathophysiology",
           "Dual mechanism: increased platelet destruction + impaired platelet production")

# Left: Destruction pathway
section_card(s, "PLATELET DESTRUCTION (Primary Mechanism)", 0.45, 1.12, 7.8, 4.3, DEEP_TEAL, TEAL_LIGHT)
destroy = [
    (0, "B CELLS produce autoantibodies — primarily IgG, directed against platelet surface glycoproteins:", True),
    (1, "GPIIb/IIIa (integrin αIIbβ3) — MOST COMMON target (~60–70%)", False),
    (1, "GPIb/IX (von Willebrand factor receptor) — second most common", False),
    (1, "Other targets: GPIa/IIa, GPIV, GPVI", False),
    (0, "Antibody-coated platelets → opsonised → FcγR-mediated phagocytosis by:", True),
    (1, "Splenic macrophages (main site) — splenectomy effective in ~80%", False),
    (1, "Hepatic Kupffer cells (secondary site) — post-splenectomy destruction here", False),
    (0, "T CELL-MEDIATED CYTOTOXICITY: CD8+ cytotoxic T cells directly kill antibody-coated platelets", False),
    (0, "T REGULATORY CELL (Treg) DEFICIENCY: loss of peripheral immune tolerance — allows autoreactive B/T cells to proliferate", False),
    (0, "COMPLEMENT activation (IgG + IgM): contributes to platelet clearance in some patients", False),
    (0, "H. pylori: molecular mimicry? Cag A protein cross-reacts with GPIIb/IIIa in some patients", False),
]
bullets(s, destroy, 0.55, 1.55, 7.65, 3.75, sz=12.5)

# Right: Impaired production
section_card(s, "IMPAIRED PLATELET PRODUCTION", 8.55, 1.12, 4.35, 4.3, AMBER, AMBER_LIGHT)
produce = [
    (0, "MEGAKARYOCYTE SUPPRESSION:", True),
    (1, "Anti-GPIIb/IIIa antibodies cross-react with megakaryocyte surface GPIIb/IIIa", False),
    (1, "→ Inhibits platelet release and proplatelet formation", False),
    (1, "→ Megakaryocyte apoptosis", False),
    (0, "THROMBOPOIETIN (TPO) paradox:", True),
    (1, "TPO levels are NOT elevated in ITP (unlike in aplastic anaemia)", False),
    (1, "Because platelets + megakaryocytes normally clear TPO", False),
    (1, "With fewer megakaryocytes, less TPO feedback", False),
    (0, "BONE MARROW findings:", True),
    (1, "Normal or increased megakaryocytes", False),
    (1, "Young/immature megakaryocytes (impaired maturation)", False),
    (1, "Normal RBC + WBC precursors (helps exclude aplasia/MDS)", False),
]
bullets(s, produce, 8.65, 1.55, 4.2, 3.75, sz=11.5)

# Bottom: therapeutic implications
rect(s, 0.45, 5.5, 12.45, 1.85, PURPLE_LIGHT, line=True)
rect(s, 0.45, 5.5, 0.07, 1.85, PURPLE)
txt(s, "Therapeutic Implications of Dual Mechanism", 0.62, 5.53, 12.0, 0.42, sz=13, bold=True, color=PURPLE)
impl = [
    (0, "Corticosteroids: ↓ FcγR expression on macrophages + ↓ antibody production + ↑ platelet production", False),
    (0, "IVIG / anti-D: saturate FcγRs → block reticuloendothelial destruction → rapid platelet rise", False),
    (0, "Rituximab (anti-CD20): depletes B cells → ↓ autoantibody production", False),
    (0, "TPO-receptor agonists (eltrombopag, romiplostim, avatrombopag): stimulate megakaryopoiesis → ↑ platelet production", False),
    (0, "Splenectomy: removes primary site of destruction AND primary B-cell autoantibody production", False),
]
bullets(s, impl, 0.62, 5.99, 12.1, 1.28, sz=12.5, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════
# SLIDE 7 — Clinical Presentation
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Clinical Presentation",
           "Predominantly mucocutaneous bleeding · May be asymptomatic (incidental finding)")

# Left: Main presentation
section_card(s, "SYMPTOMS & SIGNS", 0.45, 1.12, 7.8, 3.5, DEEP_TEAL, TEAL_LIGHT)
pres = [
    (0, "SKIN FINDINGS (most visible):", True),
    (1, "Petechiae — non-blanching, pinpoint (<2 mm); gravity-dependent (ankles, shins)", False),
    (1, "Purpura — non-blanching confluent lesions (2–10 mm)", False),
    (1, "Ecchymoses — easy bruising disproportionate to trauma", False),
    (0, "MUCOSAL BLEEDING:", True),
    (1, "Oral (gingival, mucosal): 'wet purpura' — haemorrhagic bullae in mouth → HIGH-RISK sign", False),
    (1, "Epistaxis — may be prolonged and difficult to control", False),
    (1, "Menorrhagia — heavy menstrual bleeding (major concern in reproductive-age women)", False),
    (1, "GI bleeding — melaena, haematochezia (less common)", False),
    (0, "SERIOUS / LIFE-THREATENING (rare):", True),
    (1, "Intracranial haemorrhage (ICH) — <1% but most feared; risk ↑ with platelet <10 × 10⁹/L", False),
    (1, "Retinal haemorrhage — heralds imminent severe bleeding; requires urgent treatment", False),
    (1, "Haematuria", False),
    (0, "ASYMPTOMATIC: many patients — incidental thrombocytopenia on routine CBC", False),
    (0, "PHYSICAL EXAMINATION: usually NO splenomegaly, NO lymphadenopathy, NO hepatomegaly", False),
    (0, "  → Presence of organomegaly / lymphadenopathy suggests SECONDARY cause — investigate further", False),
]
bullets(s, pres, 0.55, 1.55, 7.65, 3.0, sz=12.5)

# Right: Children vs Adults comparison
section_card(s, "CHILDREN vs ADULTS", 8.55, 1.12, 4.35, 3.5, BLUE, BLUE_LIGHT)
comp = [
    ("Feature", "Children", "Adults"),
    ("Onset", "Acute, abrupt", "Insidious, gradual"),
    ("Preceding viral", "Common (<3 wk)", "Uncommon"),
    ("Platelet nadir", "Often <20", "Variable"),
    ("Spont. remission", ">80–90%", "Rare (<10%)"),
    ("Course", "Self-limited weeks", "Chronic (>12 mo)"),
    ("Sex", "M = F", "F > M (3:1)"),
    ("Peak age", "2–6 years", ">60 years"),
    ("ICH risk", "<0.5%", "~1%"),
]
rect(s, 8.55, 1.5, 4.35, 0.38, BLUE)
for j, hdr in enumerate(comp[0]):
    xo = [8.55, 9.8, 11.2][j]; wo = [1.2, 1.35, 1.25][j]
    txt(s, hdr, xo+0.05, 1.52, wo, 0.34, sz=11, bold=True, color=WHITE, va=MSO_ANCHOR.MIDDLE)
for i, row in enumerate(comp[1:]):
    yp = 1.9 + i*0.33
    bg = BLUE_LIGHT if i%2==0 else WHITE
    rect(s, 8.55, yp, 4.35, 0.33, bg)
    for j, cell in enumerate(row):
        xo = [8.55, 9.8, 11.2][j]; wo = [1.2, 1.35, 1.25][j]
        bld = j == 0
        txt(s, cell, xo+0.05, yp+0.02, wo, 0.29, sz=11, bold=bld, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)

# Bottom warning box
rect(s, 0.45, 4.72, 12.45, 2.63, CRIMSON_LIGHT, line=True)
rect(s, 0.45, 4.72, 0.07, 2.63, CRIMSON)
txt(s, "⚠  Warning Signs Requiring URGENT Evaluation & Admission", 0.62, 4.75, 12.0, 0.42,
    sz=13, bold=True, color=CRIMSON)
warn = [
    (0, "Wet purpura (haemorrhagic oral bullae) — implies platelet count usually <10–20 × 10⁹/L", False),
    (0, "Retinal haemorrhages on fundoscopy → immediate treatment required", False),
    (0, "Headache, confusion, focal neurology → suspect intracranial haemorrhage → urgent CT head", False),
    (0, "Haemodynamic instability / haemorrhagic shock from GI or genitourinary bleeding", False),
    (0, "Platelet count <10 × 10⁹/L regardless of symptoms → consider hospitalisation", False),
]
bullets(s, warn, 0.62, 5.22, 12.1, 2.0, sz=12.5, color=CRIMSON, bullet="▶ ")

# ═══════════════════════════════════════════════════════════
# SLIDE 8 — CLINICAL IMAGE SLIDE
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Clinical & Pathological Features — Visual Gallery", "Educational imaging")

# image placeholders (will embed after script runs)
rect(s, 0.4, 1.15, 5.8, 4.2, LIGHT_GRAY, line=True)
txt(s, "[Image 1: Petechiae & Purpura in ITP]", 0.4, 1.15, 5.8, 4.2,
    sz=13, color=MED_TEXT, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE, italic=True)

rect(s, 6.55, 1.15, 6.3, 4.2, LIGHT_GRAY, line=True)
txt(s, "[Image 2: Drug-induced ITP — wet purpura, ecchymoses, petechiae composite]", 6.55, 1.15, 6.3, 4.2,
    sz=13, color=MED_TEXT, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE, italic=True)

rect(s, 0.4, 5.48, 5.8, 1.9, TEAL_LIGHT, line=True)
txt(s, "Non-blanching petechiae on lower limbs\n(characteristic of thrombocytopenic purpura, platelet count typically <20 × 10⁹/L)",
    0.45, 5.52, 5.68, 1.82, sz=12, italic=True, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)

rect(s, 6.55, 5.48, 6.3, 1.9, TEAL_LIGHT, line=True)
txt(s, "Multisite bleeding: petechiae (lower limbs), ecchymosis (axilla), wet purpura (oral mucosa)\n"
       "Wet purpura = haemorrhagic bullae in mouth — HIGH-RISK marker demanding urgent treatment",
    6.6, 5.52, 6.18, 1.82, sz=12, italic=True, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════
# SLIDE 9 — Diagnostic Approach
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Diagnostic Approach",
           "ITP is a DIAGNOSIS OF EXCLUSION — no single confirmatory test")

# Flow
steps = [
    ("Step 1", "Confirm Thrombocytopenia", "Repeat CBC; peripheral blood smear (clumps, morphology)", DEEP_TEAL, TEAL_LIGHT),
    ("Step 2", "Exclude Pseudothrombocytopenia", "Smear for platelet clumps; repeat in citrate tube", MED_TEAL, TEAL_LIGHT),
    ("Step 3", "Detailed History & Examination", "Drug history · Viral symptoms · Autoimmune symptoms · Lymphadenopathy / organomegaly", BLUE, BLUE_LIGHT),
    ("Step 4", "Mandatory Lab Tests", "FBC + differential · Blood film · HIV · HCV · HBV · Peripheral smear", AMBER, AMBER_LIGHT),
    ("Step 5", "Secondary Cause Workup", "ANA / anti-dsDNA (SLE) · APLA · Blood group (Rh) · Immunoglobulins · SPEP · H. pylori (endemic areas)", PURPLE, PURPLE_LIGHT),
    ("Step 6", "Targeted Tests if Indicated", "DAT/Coombs (Evans' syndrome) · Reticulocyte count · LDH / haptoglobin (haemolysis) · Coagulation screen · Fasting glucose (steroid baseline)", GREEN, GREEN_LIGHT),
    ("Step 7", "Bone Marrow Examination (if needed)", "NOT routine; reserve for: atypical features, age >60, failure to respond, suspicion of MDS/leukaemia, splenectomy planning", CRIMSON, CRIMSON_LIGHT),
]
for i, (step, title, desc, accent, bg) in enumerate(steps):
    yp = 1.13 + i * 0.86
    rect(s, 0.45, yp, 1.5, 0.78, accent)
    txt(s, step, 0.48, yp+0.03, 1.44, 0.72, sz=13, bold=True,
        color=WHITE, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)
    rect(s, 1.97, yp, 10.9, 0.78, bg, line=True)
    txt(s, title, 2.07, yp+0.04, 3.8, 0.36, sz=13, bold=True, color=accent)
    txt(s, desc, 2.07, yp+0.40, 10.7, 0.34, sz=12, color=DARK_TEXT)

    # Arrow (except last)
    if i < len(steps) - 1:
        rect(s, 0.9, yp + 0.78, 0.6, 0.08, accent)

# ═══════════════════════════════════════════════════════════
# SLIDE 10 — Differential Diagnosis
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Differential Diagnosis of Thrombocytopenia",
           "Categorised by mechanism — critical to distinguish from ITP")

diffs = [
    ("Increased Platelet Destruction — IMMUNE", DEEP_TEAL, TEAL_LIGHT, [
        "Primary ITP",
        "Secondary ITP (SLE, HIV, HCV, drugs)",
        "Drug-induced immune thrombocytopenia (DITP)",
        "Heparin-induced thrombocytopenia (HIT) — THROMBOSIS, not just bleeding",
        "Post-transfusion purpura (PTP)",
        "Alloimmune thrombocytopenia (neonatal)",
    ]),
    ("Increased Destruction — NON-IMMUNE (Microangiopathic)", AMBER, AMBER_LIGHT, [
        "TTP (Thrombotic Thrombocytopenic Purpura) — MAHA + neuro symptoms",
        "HUS (Haemolytic Uraemic Syndrome) — MAHA + renal failure",
        "DIC — consumption coagulopathy",
        "Preeclampsia / HELLP syndrome",
        "Antiphospholipid syndrome",
    ]),
    ("Decreased Platelet Production", PURPLE, PURPLE_LIGHT, [
        "Aplastic anaemia",
        "Myelodysplastic syndrome (MDS)",
        "Acute leukaemia / bone marrow infiltration",
        "B12/folate deficiency (macrocytic anaemia + thrombocytopenia)",
        "Alcohol-induced bone marrow suppression",
        "Chemotherapy / radiation",
    ]),
    ("Sequestration / Redistribution", BLUE, BLUE_LIGHT, [
        "Hypersplenism (any cause of splenomegaly)",
        "Chronic liver disease / portal hypertension",
        "Gaucher's disease",
        "Hypothermia (reversible splenic pooling)",
    ]),
    ("Hereditary / Congenital Causes", GREEN, GREEN_LIGHT, [
        "MYH9-related disorders (May-Hegglin anomaly) — giant platelets",
        "Bernard-Soulier syndrome",
        "Wiskott-Aldrich syndrome (X-linked)",
        "Fanconi anaemia — pancytopenia",
        "Congenital amegakaryocytic thrombocytopenia",
    ]),
]

positions = [(0.45, 1.12), (6.8, 1.12), (0.45, 3.98), (6.8, 3.98), (0.45, 6.08)]
widths = [6.1, 6.1, 6.1, 6.1, 12.45]
heights = [2.7, 2.7, 1.9, 1.9, 1.25]
for (x, y), w, h, (title, acc, bg, items) in zip(positions, widths, heights, diffs):
    section_card(s, title, x, y, w, h, acc, bg)
    bullets(s, items, x+0.12, y+0.42, w-0.22, h-0.46, sz=11.5)

# ═══════════════════════════════════════════════════════════
# SLIDE 11 — Investigations
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Investigations in ITP",
           "Goal: exclude secondary causes · Confirm isolated thrombocytopenia")

# Table format
headers = ["Investigation", "Findings in Primary ITP", "Significance"]
col_x = [0.45, 4.3, 9.1]
col_w = [3.8, 4.75, 4.05]
rect(s, 0.45, 1.12, 12.45, 0.46, DEEP_TEAL)
for j, (hdr, x, w) in enumerate(zip(headers, col_x, col_w)):
    txt(s, hdr, x+0.08, 1.14, w-0.1, 0.42, sz=13, bold=True,
        color=WHITE, va=MSO_ANCHOR.MIDDLE)

rows = [
    ("CBC", "Isolated ↓ platelets; WBC + Hb NORMAL", "Other cytopenias → secondary cause"),
    ("Peripheral Blood Smear", "Large (young) platelets; RBC + WBC morphology normal", "Fragmented RBCs → TTP/HUS; blasts → leukaemia; clumps → pseudo"),
    ("Coagulation (PT, aPTT)", "NORMAL", "Prolonged → DIC, liver disease, anticoagulant effect"),
    ("HIV serology", "Exclude HIV-associated ITP", "HIV directly causes thrombocytopenia; alters treatment"),
    ("HCV / HBV serology", "Exclude viral hepatitis", "HCV common cause secondary ITP; HBV: avoid rituximab unless covered"),
    ("ANA / anti-dsDNA", "Negative in primary ITP", "Positive → SLE (secondary ITP)"),
    ("APLA screen", "Negative in primary ITP", "Antiphospholipid syndrome causes both thrombocytopenia AND thrombosis"),
    ("Direct Antiglobulin Test (DAT)", "Negative in primary ITP", "Positive + haemolytic anaemia → Evans' syndrome"),
    ("Serum immunoglobulins / SPEP", "Normal", "Hypogammaglobulinaemia, monoclonal protein → lymphoproliferative disorder"),
    ("H. pylori testing", "Positive in endemic areas (~20%)", "Eradication may improve platelets; geographic variation in benefit"),
    ("Anti-platelet antibodies", "Low sensitivity & specificity — NOT routinely recommended", "Poor diagnostic yield; negative result does not exclude ITP"),
    ("Bone Marrow Examination", "Normal or ↑ megakaryocytes (large, immature)", "Reserved for atypical cases, failure of 1st-line Rx, age >60, pre-splenectomy"),
    ("Serum TPO level", "Normal or mildly elevated (paradoxically NOT high)", "Distinguishes from aplastic anaemia / bone marrow failure (where TPO is very high)"),
]
for i, (inv, find, sig) in enumerate(rows):
    yp = 1.6 + i * 0.42
    bg = TEAL_LIGHT if i % 2 == 0 else WHITE
    rect(s, 0.45, yp, 12.45, 0.42, bg)
    for j, (cell, x, w) in enumerate(zip([inv, find, sig], col_x, col_w)):
        bld = j == 0
        col = DEEP_TEAL if bld else DARK_TEXT
        txt(s, cell, x+0.06, yp+0.03, w-0.1, 0.36, sz=11.5, bold=bld,
            color=col, va=MSO_ANCHOR.MIDDLE)

# ═══════════════════════════════════════════════════════════
# SLIDE 12 — First-Line Treatment
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Treatment — First-Line Therapy",
           "Goal: safe platelet count (≥30 × 10⁹/L) · Minimise treatment toxicity")

# When to treat decision
rect(s, 0.45, 1.12, 12.45, 1.15, AMBER_LIGHT, line=True)
rect(s, 0.45, 1.12, 0.07, 1.15, AMBER)
txt(s, "When to Treat? (ASH 2019 Guidelines)", 0.62, 1.14, 12.0, 0.42, sz=13, bold=True, color=AMBER)
when = "Platelets <30 × 10⁹/L with active bleeding  |  Platelets <20 × 10⁹/L (even asymptomatic) → consider treatment  |  " \
       "Patients with significant bleeding risk (surgery, anticoagulation, lifestyle)  |  " \
       "Patients with platelet >30 × 10⁹/L who are ASYMPTOMATIC → observation only (no treatment needed)"
txt(s, when, 0.62, 1.58, 12.1, 0.62, sz=12.5, color=DARK_TEXT)

# Treatment agents
agents = [
    ("Corticosteroids\n(First Choice)", "MECHANISM: ↓ FcγR-mediated phagocytosis + ↓ antibody synthesis + ↑ platelet production\n\n"
     "REGIMENS:\n• Dexamethasone 40 mg/day PO/IV × 4 days (preferred — faster response)\n"
     "• Prednisone 1 mg/kg/day with gradual taper over 4–6 weeks\n\n"
     "RESPONSE: 70–80% initial response rate; however 30–40% relapse\n\n"
     "SIDE EFFECTS: Hyperglycaemia, hypertension, insomnia, psychosis, osteoporosis,\n"
     "weight gain, immunosuppression — limit long-term use",
     DEEP_TEAL, TEAL_LIGHT),
    ("IVIG — Intravenous\nImmunoglobulin", "MECHANISM: Saturates FcγRs on macrophages → temporarily blocks platelet destruction\n\n"
     "DOSE: 1 g/kg × 1–2 days (total 1–2 g/kg)\n\n"
     "USE: Rapid platelet rise needed — surgery, active severe bleeding, pre-procedure\n"
     "Used with steroids for platelet counts <10 × 10⁹/L or significant bleeding\n\n"
     "ONSET: 24–48 h  |  DURATION: 2–6 weeks (temporary!)\n\n"
     "SIDE EFFECTS: Headache, fever, hypertension, aseptic meningitis, thromboembolism, renal failure (sucrose-based preparations)",
     MED_TEAL, TEAL_LIGHT),
    ("Anti-D\nImmunoglobulin\n(Rh₀ immune globulin)", "MECHANISM: Limited haemolysis of antibody-coated RBCs saturates FcγRs → blocks platelet destruction\n\n"
     "DOSE: 50–75 μg/kg IV\n\n"
     "ONLY in: Rh-positive, non-splenectomised patients\n\n"
     "FDA BLACK BOX WARNING: Severe intravascular haemolysis (rare) → 8h post-infusion monitoring mandatory\n\n"
     "NOTE: Less commonly used now given available safer alternatives; ineffective post-splenectomy",
     AMBER, AMBER_LIGHT),
]
for i, (name, desc, accent, bg) in enumerate(agents):
    x = 0.45 + i*4.29
    rect(s, x, 2.37, 4.22, 0.46, accent)
    txt(s, name, x+0.1, 2.39, 4.0, 0.42, sz=13, bold=True,
        color=WHITE, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)
    rect(s, x, 2.83, 4.22, 4.52, bg, line=True)
    txt(s, desc, x+0.12, 2.87, 3.98, 4.44, sz=11.5, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════
# SLIDE 13 — Second-Line: Rituximab & TPO-RAs
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Treatment — Second-Line: Rituximab & TPO-Receptor Agonists",
           "For persistent/chronic ITP unresponsive to 1st-line · Preferred over early splenectomy")

# When second-line
rect(s, 0.45, 1.12, 12.45, 0.72, AMBER_LIGHT, line=True)
rect(s, 0.45, 1.12, 0.07, 0.72, AMBER)
txt(s, "Indications for Second-Line Therapy", 0.62, 1.15, 12.0, 0.38, sz=13, bold=True, color=AMBER)
txt(s, "Relapsed or refractory after 1st-line steroids (30–40% of adults)  |  "
       "Steroid-dependent  |  Steroid intolerance/contraindication  |  Persistent ITP (3–12 months)  |  "
       "Chronic ITP >12 months — currently ASH recommends TPO-RA or rituximab over early splenectomy",
    0.62, 1.55, 12.1, 0.24, sz=12, color=DARK_TEXT)

# Rituximab column
section_card(s, "RITUXIMAB (Anti-CD20 Monoclonal Antibody)", 0.45, 1.95, 6.0, 5.4, BLUE, BLUE_LIGHT)
ritu = [
    (0, "TARGET: CD20 on B cells → B-cell depletion → ↓ autoantibody production", False),
    (0, "DOSE: 375 mg/m² IV weekly × 4 doses (standard) OR 100 mg/m² low-dose × 4 weekly doses", False),
    (0, "RESPONSE RATES:", True),
    (1, "Initial response: ~60% of patients", False),
    (1, "Sustained response at 1 year: ~40%", False),
    (1, "Durable complete response at 5 years: ~20–30%", False),
    (0, "ONSET: 4–8 weeks (NOT for urgent/emergency treatment)", False),
    (0, "Re-treatment: retreatment possible if relapse; some patients respond again", False),
    (0, "SIDE EFFECTS:", True),
    (1, "Infusion reactions (pre-medicate with steroids/antihistamines)", False),
    (1, "Hypogammaglobulinaemia (check IgG levels pre-/post-treatment)", False),
    (1, "HBV reactivation → screen ALL patients for HBV before treatment; prophylactic antivirals if HBsAg+ or anti-HBc+", False),
    (1, "Progressive multifocal leukoencephalopathy (PML) — rare but reported", False),
    (1, "Prolonged B-cell depletion: 6–12 months", False),
    (0, "NOT FDA-approved for ITP but widely used off-label (evidence from multiple RCTs)", False),
]
bullets(s, ritu, 0.55, 2.38, 5.8, 4.85, sz=12)

# TPO-RA column
section_card(s, "TPO-RECEPTOR AGONISTS (TPO-RA)", 6.75, 1.95, 6.15, 5.4, PURPLE, PURPLE_LIGHT)
tpo = [
    (0, "MECHANISM: Mimic endogenous TPO → bind c-Mpl receptor on megakaryocytes → ↑ platelet production", False),
    (0, "THREE APPROVED TPO-RAs (all FDA-approved for chronic ITP):", True),
    (1, "ROMIPLOSTIM (Nplate): SC injection weekly; peptibody; 1–10 μg/kg/week; dose-titrated", False),
    (1, "ELTROMBOPAG (Promacta): oral once daily; 25–75 mg; small molecule non-peptide", False),
    (1, "AVATROMBOPAG (Doptelet): oral once daily; 20–40 mg; newest agent", False),
    (0, "RESPONSE RATES:", True),
    (1, "Durable platelet improvement in >90% of patients", False),
    (1, "Response onset: 5–14 days", False),
    (1, "10–30% maintain durable response even after stopping therapy", False),
    (0, "ADVANTAGES over splenectomy/rituximab: maintained on long-term with good efficacy; can reduce/stop other therapies", False),
    (0, "SIDE EFFECTS:", True),
    (1, "Thromboembolic events (DVT, PE, portal vein thrombosis) — monitor for symptoms", False),
    (1, "Bone marrow reticulin fibrosis (rare; romiplostim > eltrombopag) — monitor with BM biopsy if on long-term", False),
    (1, "Eltrombopag: hepatotoxicity (LFT monitoring required), avoid with antacids/calcium (chelation)", False),
    (1, "Rebound thrombocytopenia on abrupt withdrawal — taper carefully", False),
    (0, "NOTE: Fostamatinib (SYK inhibitor) and Inebilizumab/FcRn inhibitors: newer agents for refractory ITP", False),
]
bullets(s, tpo, 6.85, 2.38, 5.95, 4.85, sz=11.5)

# ═══════════════════════════════════════════════════════════
# SLIDE 14 — Splenectomy
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "Treatment — Splenectomy",
           "Historical gold standard · Now deferred to ≥12 months · ~80% initial response")

section_card(s, "Rationale & Timing", 0.45, 1.12, 6.0, 2.8, DEEP_TEAL, TEAL_LIGHT)
rat = [
    "Spleen: PRIMARY site of anti-platelet IgG production AND platelet destruction",
    "Removes both the 'factory' and the 'graveyard' of antibody-coated platelets",
    "ASH 2019: Defer splenectomy to ≥12 months (chronic ITP); allow time for medical therapy response",
    "Consider earlier if: life-threatening bleeding, failure of all medical therapies, patient preference to avoid long-term drugs",
    "Emergency splenectomy: reserved for life-threatening, medically refractory bleeding",
    "Pre-op: vaccination ≥2 weeks before surgery (pneumococcus, meningococcus, H. influenzae type b)",
]
bullets(s, rat, 0.55, 1.55, 5.8, 2.3, sz=12.5)

section_card(s, "Response Rates", 6.75, 1.12, 6.1, 2.8, GREEN, GREEN_LIGHT)
resp = [
    "INITIAL response rate: ~80% (immediate platelet rise post-operatively)",
    "LONG-TERM remission (no further treatment): ~60% at 5 years",
    "PARTIAL response (still need medical therapy): ~20%",
    "FAILURE / RELAPSE: ~20% — consider accessory spleen (5–7% of cases)",
    "Accessory spleen: excluded pre-operatively by technetium scan or CT",
    "Post-splenectomy: if relapse, check for missed accessory spleen",
]
bullets(s, resp, 6.85, 1.55, 5.9, 2.3, sz=12.5)

section_card(s, "Contraindications to Splenectomy", 0.45, 4.02, 6.0, 1.95, CRIMSON, CRIMSON_LIGHT)
contra = [
    "Newly diagnosed ITP (< 3–6 months)",
    "Adequate response to medical therapy",
    "High surgical risk (severe comorbidities)",
    "Pregnancy (relative; can be done in 2nd trimester if life-threatening)",
    "Severe bleeding disorder not yet controlled",
]
bullets(s, contra, 0.55, 4.45, 5.8, 1.48, sz=12.5)

section_card(s, "Post-Splenectomy Care & Risks", 6.75, 4.02, 6.1, 1.95, AMBER, AMBER_LIGHT)
post = [
    "OPSI (Overwhelming Post-Splenectomy Infection): lifelong risk; most common in first 2 years",
    "Causative organisms: S. pneumoniae, N. meningitidis, H. influenzae",
    "VACCINATION: Pneumococcal (PCV13 + PPSV23), meningococcal, Hib, annual influenza",
    "PROPHYLACTIC ANTIBIOTICS: Penicillin V 250–500 mg BD (consider in first 2 years and asplenic)",
    "Educate: seek immediate medical attention for fever ≥38°C post-splenectomy",
]
bullets(s, post, 6.85, 4.45, 5.9, 1.48, sz=12.5)

# Approach algorithm bottom
rect(s, 0.45, 6.05, 12.45, 1.35, WHITE, line=True)
rect(s, 0.45, 6.05, 0.07, 1.35, DEEP_TEAL)
txt(s, "Current Preferred Treatment Sequence (ASH 2019)", 0.62, 6.08, 12.0, 0.42, sz=13, bold=True, color=DEEP_TEAL)
txt(s, "Newly Diagnosed → Corticosteroids ± IVIG  →  Persistent/Chronic: TPO-RA or Rituximab  →  Splenectomy only if refractory/chronic (>12 months)  →  Refractory post-splenectomy: novel agents (fostamatinib, FcRn inhibitors)",
    0.62, 6.52, 12.1, 0.78, sz=12.5, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════
# SLIDE 15 — Emergency Management
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Emergency Management — Severe / Life-Threatening ITP",
           "Platelet <10 × 10⁹/L + active bleeding · Target platelet ≥50–100 × 10⁹/L urgently")

rect(s, 0.45, 1.12, 12.45, 0.6, CRIMSON_LIGHT, line=True)
rect(s, 0.45, 1.12, 0.07, 0.6, CRIMSON)
txt(s, "Indications for Emergency Treatment", 0.62, 1.15, 12.0, 0.3, sz=13, bold=True, color=CRIMSON)
txt(s, "ICH / intracranial haemorrhage  |  Retinal haemorrhage  |  Wet purpura + platelet <10 × 10⁹/L  |  Major GI/GU bleed  |  "
       "Haemodynamic instability  |  Pre-emergency surgery  |  Platelet <5 × 10⁹/L (any circumstance)",
    0.62, 1.47, 12.1, 0.2, sz=12, color=DARK_TEXT)

# Cascade
steps_emg = [
    ("IMMEDIATE", "High-dose IV methylprednisolone 1000 mg/day × 3 days\nOR Dexamethasone 40 mg IV × 4 days", CRIMSON),
    ("+", "IVIG 1 g/kg IV (repeat if needed); consider 2nd dose at 24–48 h if inadequate response", MED_TEAL),
    ("+", "PLATELET TRANSFUSION: Not standard in ITP (antibodies destroy transfused platelets too)\n"
          "BUT: use for life-threatening bleeding (ICH) — give in high doses; short-lived effect; combined with IVIG",
     AMBER),
    ("+", "Anti-D immunoglobulin 75 μg/kg (if Rh+, non-splenectomised, Hb adequate)", BLUE),
    ("+", "TPO-RA (eltrombopag or romiplostim): start ASAP — takes 5–14 days to work; bridge with above agents", PURPLE),
    ("If no\nresponse", "Consider: Rituximab high-dose  |  Recombinant factor VIIa (rFVIIa)  |  Vincristine  |  Danazol\n"
                        "EMERGENCY SPLENECTOMY as last resort for refractory life-threatening bleeding",
     DEEP_TEAL),
]
y_s = 1.82
for label, desc, accent in steps_emg:
    h = 0.78 if len(desc) > 120 else 0.65
    rect(s, 0.45, y_s, 1.5, h, accent)
    txt(s, label, 0.48, y_s+0.04, 1.44, h-0.08, sz=12.5, bold=True,
        color=WHITE, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)
    rect(s, 1.98, y_s, 11.0, h, LIGHT_GRAY if y_s % 2 > 1 else WHITE, line=True)
    txt(s, desc, 2.08, y_s+0.04, 10.8, h-0.08, sz=12, color=DARK_TEXT)
    y_s += h + 0.06

# ═══════════════════════════════════════════════════════════
# SLIDE 16 — Special Populations
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
header_bar(s, "ITP in Special Populations",
           "Paediatric · Pregnancy · Elderly · HIV-associated")

pops = [
    ("ITP IN CHILDREN", DEEP_TEAL, TEAL_LIGHT, [
        "Acute, post-viral (1–3 weeks after viral illness / vaccine)",
        "Platelet <20 × 10⁹/L common, >80% spontaneous remission within weeks–months",
        "Management: observation if mild bleeding (skin only) even with platelet <20 × 10⁹/L",
        "Treatment when needed: IVIG 0.8–1 g/kg, prednisone, or anti-D",
        "AVOID routine bone marrow biopsy unless atypical features or failure of 1st-line",
        "Splenectomy deferred until >12 months; very rarely needed in children",
        "Re-evaluate at 12 months — if platelet <20 or significant symptoms → chronic ITP treatment",
    ]),
    ("ITP IN PREGNANCY", AMBER, AMBER_LIGHT, [
        "Incidence: ~1 in 1,000–10,000 pregnancies — must distinguish from gestational thrombocytopenia (GT)",
        "GT: Platelet rarely <70 × 10⁹/L; 1st/2nd trimester decline; no neonatal thrombocytopenia",
        "ITP: pre-existing or new diagnosis; neonatal thrombocytopenia risk (<10 × 10⁹/L) in ~10% neonates",
        "Treatment: Prednisolone 10–20 mg/day; IVIG 1 g/kg; target platelet ≥30 (T1/T2), ≥50 (T3), ≥80 (neuraxial anaesthesia)",
        "AVOID: anti-D (risk to Rh+ foetus), azathioprine (teratogenic), mycophenolate, cyclophosphamide",
        "H. pylori eradication: defer until after delivery",
        "Mode of delivery: vaginal delivery preferred; Caesarean for obstetric indications only",
        "Neonates: check platelet count at birth; monitor if <50 × 10⁹/L",
    ]),
    ("ITP IN HIV", PURPLE, PURPLE_LIGHT, [
        "HIV directly infects megakaryocytes → ↓ production; also immune-mediated destruction",
        "HAART (antiretroviral therapy) is first-line — often improves platelet count",
        "Avoid immunosuppression (steroids) if CD4 <200 cells/μL",
        "IVIG: safe and effective bridge therapy",
        "Splenectomy: effective but increases risk of opportunistic infections — only for refractory cases",
        "TPO-RAs: effective and generally safe; preferred in HIV-ITP",
    ]),
    ("ELDERLY PATIENTS", BLUE, BLUE_LIGHT, [
        "More complex presentation — comorbidities, polypharmacy (drug-induced ITP common)",
        "Higher risk of both bleeding AND treatment complications",
        "Steroid side effects exacerbated: diabetes, hypertension, osteoporosis, delirium",
        "TPO-RAs: preferred over steroids or splenectomy where possible",
        "Thromboembolism risk higher with TPO-RA — monitor closely",
        "Secondary ITP more common (MDS, lymphoma) — BM biopsy lower threshold",
    ]),
]

positions = [(0.45, 1.12), (6.8, 1.12), (0.45, 4.28), (6.8, 4.28)]
widths2 = [6.1, 6.1, 6.1, 6.1]
heights2 = [3.0, 3.0, 3.07, 3.07]
for (x, y), w, h, (title, acc, bg, items) in zip(positions, widths2, heights2, pops):
    section_card(s, title, x, y, w, h, acc, bg)
    bullets(s, items, x+0.12, y+0.42, w-0.22, h-0.46, sz=11.5)

# ═══════════════════════════════════════════════════════════
# SLIDE 17 — Monitoring & Follow-up
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, WHITE)
header_bar(s, "Monitoring & Follow-up",
           "Tailored by disease phase, treatment, and bleeding risk")

# Phases table
phases_mon = [
    ("NEWLY DIAGNOSED\n(0–3 months)", "• CBC weekly initially, then every 2 weeks\n"
     "• Assess bleeding symptoms at each visit\n• Monitor steroid side effects (glucose, BP, weight)\n"
     "• Document treatment response\n• Screen for secondary causes (HIV, HCV, ANA if not done)\n"
     "• TARGET: Platelet ≥30 × 10⁹/L safely", DEEP_TEAL, TEAL_LIGHT),
    ("PERSISTENT ITP\n(3–12 months)", "• CBC every 4 weeks during treatment\n"
     "• Reassess: Is treatment still needed?\n• Consider 2nd-line if relapsed or steroid-dependent\n"
     "• Start TPO-RA or rituximab if persistent symptoms\n"
     "• Patient education: bleeding precautions, emergency contact\n"
     "• Avoid NSAIDs, antiplatelet drugs", AMBER, AMBER_LIGHT),
    ("CHRONIC ITP\n(>12 months)", "• CBC every 4–12 weeks (depending on stability)\n"
     "• Annual reassessment of treatment need\n• Long-term TPO-RA: LFTs (eltrombopag), bone marrow reticulin monitoring\n"
     "• Splenectomy discussion if refractory + patient preference\n"
     "• Vaccinations if splenectomy planned\n• Bone density monitoring if long-term steroids", PURPLE, PURPLE_LIGHT),
    ("ON TPO-RAs\n(Maintenance)", "• CBC weekly for first month → monthly when stable\n"
     "• Eltrombopag: LFTs monthly initially; avoid dairy/antacids (chelation)\n"
     "• Romiplostim: weekly CBC; dose adjustment by response\n"
     "• Monitor for thromboembolic symptoms\n"
     "• If platelet >400 × 10⁹/L → dose reduction\n"
     "• Attempt TPO-RA taper when platelet stable ≥100 × 10⁹/L", GREEN, GREEN_LIGHT),
    ("POST-SPLENECTOMY", "• CBC weekly × 4 weeks post-op, then monthly × 3 months, then quarterly\n"
     "• Assess for OPSI: educate patient; medical alert bracelet\n"
     "• Booster vaccinations per schedule (pneumococcal every 5 years)\n"
     "• If relapse: check accessory spleen (Tc-99m scan/CT)\n"
     "• Monitor for rebound thrombocytosis (platelet >1000 × 10⁹/L) — transient, rarely thrombogenic", CRIMSON, CRIMSON_LIGHT),
    ("REMISSION / OFF\nTHERAPY", "• CBC every 6–12 months\n"
     "• Recheck if any bleeding symptoms develop\n"
     "• Educate: avoid NSAIDs/antiplatelet agents\n"
     "• Maintain immunisations current\n"
     "• Reassess if any new illness, medication change, or pregnancy planned\n"
     "• Low threshold to re-check platelet if viral illness / new drug started", BLUE, BLUE_LIGHT),
]

for i, (phase, plan, acc, bg) in enumerate(phases_mon):
    col = i % 2; row = i // 2
    x = 0.45 + col * 6.45; y = 1.12 + row * 2.1
    w = 6.05; h = 1.95
    section_card(s, phase, x, y, w, h, acc, bg)
    txt(s, plan, x+0.12, y+0.42, w-0.22, h-0.46, sz=11, color=DARK_TEXT)

# ═══════════════════════════════════════════════════════════
# SLIDE 18 — Key Take-Home Messages
# ═══════════════════════════════════════════════════════════
s = prs.slides.add_slide(blank)
rect(s, 0, 0, 13.333, 7.5, OFF_WHITE)
rect(s, 0, 0, 13.333, 1.0, DEEP_TEAL)
rect(s, 0, 1.0, 13.333, 0.06, MED_TEAL)
txt(s, "Key Take-Home Messages", 0.3, 0.08, 12.8, 0.84,
    sz=30, bold=True, color=WHITE, va=MSO_ANCHOR.MIDDLE)

msgs = [
    ("1", "ITP is immune-mediated DUAL pathology: platelet destruction + impaired production. TPO-RAs address both.", DEEP_TEAL, TEAL_LIGHT),
    ("2", "ITP is a DIAGNOSIS OF EXCLUSION. Always exclude pseudothrombocytopenia (check smear) and secondary causes (HIV, HCV, SLE, drugs).", BLUE, BLUE_LIGHT),
    ("3", "Treat when platelet <30 × 10⁹/L or <20 × 10⁹/L asymptomatically. Platelet ≥30 without bleeding = observe.", AMBER, AMBER_LIGHT),
    ("4", "Wet purpura (oral haemorrhagic bullae) + retinal haemorrhages = EMERGENCY. Admit, combined-modality treatment immediately.", CRIMSON, CRIMSON_LIGHT),
    ("5", "Children: >80% spontaneous remission — avoid aggressive early treatment. Adults: chronic disease; relapse common.", GREEN, GREEN_LIGHT),
    ("6", "ASH 2019: Prefer TPO-RA or rituximab over early splenectomy. Defer splenectomy to ≥12 months.", PURPLE, PURPLE_LIGHT),
    ("7", "Before rituximab: screen ALL patients for HBV. Administer prophylactic antivirals if HBsAg+ or anti-HBc+.", MED_TEAL, TEAL_LIGHT),
    ("8", "Post-splenectomy: vaccinate ≥2 weeks pre-op; life-long OPSI risk; educate on fever emergency protocol.", AMBER, AMBER_LIGHT),
]

for i, (num, msg, acc, bg) in enumerate(msgs):
    col = i % 2; row = i // 2
    x = 0.45 + col * 6.45; y = 1.14 + row * 1.52
    w = 6.05; h = 1.42
    rect(s, x, y, w, h, bg, line=True)
    rect(s, x, y, 0.55, h, acc)
    txt(s, num, x, y+0.02, 0.55, h-0.04, sz=24, bold=True,
        color=WHITE, align=PP_ALIGN.CENTER, va=MSO_ANCHOR.MIDDLE)
    txt(s, msg, x+0.62, y+0.1, w-0.7, h-0.2, sz=12.5, color=DARK_TEXT, va=MSO_ANCHOR.MIDDLE)

txt(s, "Sources: Harrison's 22e (2025) · Goldman-Cecil Medicine · Washington Manual · Rosen's EM · Sabiston Surgery · Fischer's Mastery of Surgery",
    0.45, 7.2, 12.45, 0.25, sz=10, italic=True, color=MED_TEXT, align=PP_ALIGN.CENTER)

# ─── SAVE ──────────────────────────────────────────────────
out = "/tmp/workspace/itp-presentation/ITP_Postgraduate_IM.pptx"
prs.save(out)
print(f"Saved: {out}")
print(f"Slides: {len(prs.slides)}")
Running Command

cd /tmp/workspace/itp-presentation && python build_itp.py 2>&1

Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.