1.Malaria- Pathogenesis,morphology* 2.Cysticercoisis-etiopathogenesis,morphology 3.Leprosy-pathogenesis,classify,gross and microscopic Findings *** 4.Common viral and fungal infections 5. Primary Tuberculosis- pathogenesis,common sites,Evolution of tubercle,Primary complex - components * 6.Ghons complex - Gross,microscopic features and fate***2 mbbs pathology refer robbin add easy to draw diagram coloured , answer all question important topics frequently ask topic in muhs exam systemically aswer all

Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Here are your complete, exam-ready MUHS Pathology notes based on Robbins & Kumar (Pathologic Basis of Disease, 10e and Basic Pathology):

2nd MBBS PATHOLOGY - MUHS EXAM NOTES

(Based on Robbins & Kumar Pathology)


1. MALARIA - Pathogenesis & Morphology ⭐

Etiology

Five species: P. falciparum (most virulent), P. vivax, P. ovale, P. malariae, P. knowlesi. Transmitted by the female Anopheles mosquito. Humans are the only natural reservoir.

Life Cycle / Pathogenesis

┌─────────────────────────────────────────────────────────────────┐
│              LIFE CYCLE OF PLASMODIUM FALCIPARUM                │
│                                                                 │
│  Mosquito bites human                                           │
│       ↓                                                         │
│  SPOROZOITES enter blood → travel to LIVER                      │
│  (bind to hepatocytes via thrombospondin & circumsporozoite     │
│   surface proteins)                                             │
│       ↓ (Exo-erythrocytic stage - ASYMPTOMATIC)                 │
│  Sporozoites → MEROZOITES (up to 30,000 per hepatocyte)         │
│  Infected hepatocytes RUPTURE → merozoites released             │
│  [P. vivax / P. ovale → form HYPNOZOITES → relapses]            │
│       ↓                                                         │
│  Merozoites invade RBCs (bind sialic acid on glycophorin)       │
│  [Erythrocytic stage - SYMPTOMATIC]                             │
│       ↓                                                         │
│  Merozoite → TROPHOZOITE → SCHIZONT → new Merozoites            │
│  (PfEMP1 knobs appear on RBC surface)                           │
│       ↓                                                         │
│  RBC LYSIS → fever, chills, rigors (TNF release)               │
│       ↓                                                         │
│  Some trophozoites → GAMETOCYTES (sexual forms)                 │
│  → mosquito ingests gametocytes → cycle restarts                │
└─────────────────────────────────────────────────────────────────┘

Why P. falciparum is More Virulent:

  1. Infects RBCs of ALL ages (not just young/old) → very high parasitemia
  2. PfEMP1 on RBC surface knobs - binds endothelial ICAM-1, VCAM-1, CD36, E-selectin → SEQUESTRATION in capillaries → blocks blood flow → cerebral malaria
  3. Rosette formation - infected RBCs clump together
  4. No hypnozoites - rupture occurs in 8-12 weeks

Fever Periodicity:

  • P. vivax / P. ovale: 48h (tertian - every 3rd day)
  • P. malariae: 72h (quartan - every 4th day)
  • P. falciparum: irregular (malignant tertian)

Host Protection:

  • Sickle cell trait, G6PD deficiency, Duffy antigen negativity (P. vivax) are protective
  • West Africans lack Duffy antigen → not susceptible to P. vivax

Morphology

ORGAN          │ GROSS/MICRO FINDINGS
───────────────┼──────────────────────────────────────────────────
SPLEEN         │ Splenomegaly (may exceed 1000g)
               │ Red pulp congestion + hyperplasia
               │ Gray/black hemozoin pigment in macrophages
               │ Chronic: fibrotic, thick capsule, brittle
───────────────┼──────────────────────────────────────────────────
LIVER          │ Enlarged, pigmented
               │ Kupffer cells laden with malarial pigment,
               │ parasitized RBCs, cellular debris
───────────────┼──────────────────────────────────────────────────
BRAIN          │ (P. falciparum - Cerebral Malaria)
(CEREBRAL)     │ Vessels PLUGGED with parasitized RBCs
               │ Ring hemorrhages around vessels
               │ Malarial granuloma (Dürck granuloma)
               │ Neuronal degeneration, focal ischemic softening
───────────────┼──────────────────────────────────────────────────
KIDNEY         │ Enlarged, congested
               │ Malarial pigment in glomeruli
               │ Hemoglobin casts in tubules
               │ (Blackwater fever - massive hemolysis)
───────────────┼──────────────────────────────────────────────────
BONE MARROW /  │ Pigmented phagocytic cells throughout
LYMPH NODES    │ Hemozoin pigment
───────────────┼──────────────────────────────────────────────────
BLOOD SMEAR    │ Giemsa stain: parasites inside RBCs
               │ Ring trophozoites, schizonts, gametocytes

Diagnostic Test: Giemsa-stained peripheral blood smear (gold standard)


2. CYSTICERCOSIS - Etiopathogenesis & Morphology ⭐

Etiology

  • Caused by Taenia solium (pork tapeworm) larval stage
  • Disease = human acts as INTERMEDIATE host (ingests eggs)
  • Normal: pigs are intermediate host, humans are definitive host (harbor adult worm)
  • Cysticercosis occurs when human ingests T. solium eggs (from contaminated food/water/fecal-oral route, or autoinfection via reverse peristalsis)

Etiopathogenesis

┌──────────────────────────────────────────────────────────────────┐
│                 CYSTICERCOSIS PATHOGENESIS                       │
│                                                                  │
│  Human ingests T. solium EGGS (contaminated food/water)          │
│       ↓                                                          │
│  Eggs hatch in intestine → ONCOSPHERES (hexacanth embryos)       │
│       ↓                                                          │
│  Oncospheres penetrate intestinal wall                           │
│       ↓                                                          │
│  Enter bloodstream → disseminate to TISSUES                      │
│       ↓                                                          │
│  Develop into CYSTICERCI (fluid-filled cysts with scolex inside) │
│                                                                  │
│  Preferred sites: Brain (most dangerous), subcutaneous tissue,   │
│                   eye, muscle, heart, liver                      │
│                                                                  │
│  ALIVE CYST: minimal inflammation (immune evasion)              │
│       ↓ (when cyst dies)                                         │
│  DEAD/DEGENERATING CYST: intense inflammation                    │
│  → eosinophils, neutrophils, macrophages surround cyst           │
│  → fibrous capsule formation                                     │
│  → CALCIFICATION (seen on CT scan)                               │
└──────────────────────────────────────────────────────────────────┘

Clinical Manifestations by Site:

  • Neurocysticercosis (NCC): Seizures (most common cause of acquired epilepsy in endemic areas), headache, raised ICP, hydrocephalus
  • Ocular: Visual disturbances, blindness
  • Subcutaneous: Palpable nodules

Morphology

Gross:

  • Cysticercus cellulosae: Round/oval, translucent, fluid-filled cyst
  • Size: 0.5-2 cm (usually), up to 20 cm (racemose form in brain)
  • Wall is white, glistening
  • Scolex (invaginated head) visible inside as white nodule
  • In brain: cysts in cortex, basal ganglia, ventricles
  • Racemose variant: grapelike, no scolex, in cisterns/ventricles

Microscopic:

STAGE           │ MICROSCOPIC FEATURES
────────────────┼───────────────────────────────────────────────
VIABLE CYST     │ - Outer cuticular layer (lamellar)
                │ - Middle cellular (reticular) layer
                │ - Inner germinal layer
                │ - Scolex with suckers and hooklets visible
                │ - Minimal host inflammatory response
────────────────┼───────────────────────────────────────────────
DEGENERATING/   │ - Cyst wall hyalinizes and breaks down
DEAD CYST       │ - INTENSE INFLAMMATION:
                │   Eosinophils, neutrophils, lymphocytes,
                │   plasma cells, macrophages
                │ - Granuloma formation
                │ - Giant cell reaction
────────────────┼───────────────────────────────────────────────
CALCIFIED CYST  │ - Dense calcification of dead scolex and wall
                │ - Fibrosis/gliosis around it (in brain)

3. LEPROSY - Pathogenesis, Classification, Gross & Microscopic ⭐⭐⭐

Etiology

  • Mycobacterium leprae (and rarely M. lepromatosis)
  • Slow progressive infection affecting skin and peripheral nerves
  • Cannot be cultured in vitro
  • Proliferates best at 32-34°C (cool tissues, extremities)
  • Transmission: human respiratory secretions (main route)

Pathogenesis

M. leprae enters via respiratory tract
       ↓
Taken up by DERMAL MACROPHAGES
       ↓
Disseminates via blood → replicates in COOL TISSUES
(skin, extremities, peripheral nerves)
       ↓
M. leprae: obligate intracellular → uses PGL-1 lipid for cell invasion
         → inhibits mitochondrial energy metabolism
         → evades host immune response
       ↓
┌────────────────────────────────────┐
│    HOST IMMUNE RESPONSE decides    │
│        the TYPE OF LEPROSY         │
└────────────────────────────────────┘
         ↙                     ↘
  STRONG Th1                WEAK Th1
(IL-2, IFN-γ, Th17)      (Th2 dominant/
  response                Reg T cells)
         ↓                      ↓
 TUBERCULOID              LEPROMATOUS
  LEPROSY                  LEPROSY
(Paucibacillary)          (Multibacillary)
 Low organisms,            High organisms,
  Granulomas               No granulomas

Key Immunology:

FeatureTuberculoidLepromatous
T-cell responseStrong Th1 (IFN-γ, IL-2)Weak Th1, Th2 dominant
Bacterial loadLow (paucibacillary)High (multibacillary)
AntibodiesLowHigh (but NOT protective)
CMIIntactDeficient
Lepromin testPositiveNegative

Classification (Ridley-Jopling + WHO)

SPECTRUM OF LEPROSY:

Tuberculoid (TT) ←──── Borderline ────→ Lepromatous (LL)
      │          BT    BB    BL              │
   Strong                               Weak
  Immunity                           Immunity
Paucibacillary                     Multibacillary
WHO Classification (Clinically used):
  • Paucibacillary (PB): 1-5 skin lesions (Tuberculoid/Borderline T)
  • Multibacillary (MB): >5 skin lesions (Lepromatous/Borderline L)

Gross (Clinical) Findings

Tuberculoid Leprosy:

  • Flat, red skin lesions that enlarge
  • Irregular shapes with indurated, elevated, hyperpigmented margins
  • Depressed, pale centers (central healing)
  • Anesthetic (loss of sensation - damaged nerves)
  • Asymmetric large peripheral nerve involvement
  • Nerve thickening: ulnar, radial, common peroneal, great auricular nerves
  • Skin and muscle atrophy, chronic ulcers, contractures, autoamputation of digits

Lepromatous Leprosy:

  • Symmetric skin thickening
  • Macular, papular, or nodular lesions on face, ears, wrists, elbows, knees
  • Coalescence of nodules → Leonine facies (lion-like face)
  • Most skin lesions are hyposthetic or anesthetic
  • Saddle nose deformity (nasal septum destruction)
  • Persistent nasal discharge with bacilli
  • Gynecomastia + testicular destruction → sterility
  • Symmetric nerve involvement (ulnar, peroneal nerves)

Microscopic Findings

TUBERCULOID LEPROSY:
┌──────────────────────────────────────────────────────┐
│  - Well-formed GRANULOMAS (like TB granulomas)       │
│  - Epithelioid cells + Langhans giant cells          │
│  - Dense lymphocytic infiltrate                     │
│  - Granulomas enclose and DESTROY NERVES            │
│  - Bacilli ABSENT or very rare (AFB stain negative) │
│  - Granulomas extend to basal layer of epidermis    │
└──────────────────────────────────────────────────────┘

LEPROMATOUS LEPROSY:
┌──────────────────────────────────────────────────────┐
│  - Large aggregates of LIPID-LADEN MACROPHAGES       │
│    = LEPRA CELLS (Virchow cells / foam cells)        │
│  - Lepra cells filled with GLOBI (masses of AFB)     │
│  - AFB in globi = "cigar bundles" or "cannon balls"  │
│  - NO granulomas (absent cell-mediated immunity)     │
│  - Grenz zone: subepidermal clear zone               │
│  - Lymph nodes: bacteria-filled foamy macrophages    │
│    in paracortical (T-cell) areas + reactive GCs    │
│  - Testes: destruction of seminiferous tubules       │
│  - Nerves: invaded by mycobacteria with MINIMAL      │
│    inflammation                                      │
└──────────────────────────────────────────────────────┘

Easy-to-Draw Diagram - Lepra Cell:

     LEPRA CELL (Lepromatous Leprosy)
          ┌─────────────────────┐
          │    Macrophage        │
          │  ╔═══╗ ╔═══╗ ╔═══╗  │
          │  ║AFB║ ║AFB║ ║AFB║  │  ← Globi (masses of
          │  ╚═══╝ ╚═══╝ ╚═══╝  │     acid-fast bacilli)
          │     Foamy cytoplasm  │
          │         (lipid)      │
          │      [Nucleus]       │
          └─────────────────────┘
Stain: Ziehl-Neelsen (AFB stain) - red bacilli on blue background

4. COMMON VIRAL AND FUNGAL INFECTIONS ⭐

A. Common Viral Infections

1. INFLUENZA

  • Single-stranded RNA virus, 8-segment genome
  • Surface proteins: Hemagglutinin (H) and Neuraminidase (N)
  • Type A infects humans, pigs, horses, birds (major epidemic cause)
  • Antigenic Drift: point mutations in H and N → epidemics
  • Antigenic Shift: recombination with animal viruses → pandemics
  • 1918 pandemic (swine origin, 20-40 million deaths); 2009 H1N1 pandemic

2. CORONAVIRUSES / COVID-19

  • SARS-CoV-2 (COVID-19): spike protein binds ACE2 on nasopharyngeal epithelium + type 2 alveolar cells
  • Pathogenesis: virus replication → DAD (Diffuse Alveolar Damage) → Type II pneumocyte injury → hyaline membranes
  • Severe COVID: coagulopathy, microthrombi, myocarditis, CNS inflammatory infiltrates
  • Treatment: dexamethasone (immunosuppression), low-dose anticoagulants

3. HERPES SIMPLEX VIRUS (HSV)

  • Cowdry type A inclusion bodies (intranuclear eosinophilic)
  • Multinucleated giant cells
  • HSV-1: oral/facial; HSV-2: genital

4. CYTOMEGALOVIRUS (CMV)

  • Large cells with "owl-eye" intranuclear inclusions
  • Dangerous in immunocompromised (AIDS, transplant patients)

5. MEASLES (Rubeola)

  • Warthin-Finkeldey giant cells (multinucleated giant cells with inclusions) in lymphoid organs
  • Koplik spots on buccal mucosa
  • Squamous metaplasia of bronchial epithelium

B. Common Fungal Infections

1. CANDIDIASIS

  • Candida albicans (most common)
  • Pseudohyphae + budding yeast on PAS / GMS stain
  • Superficial: thrush (oral), vulvovaginal
  • Deep: esophageal candidiasis, systemic (neutropenic patients)
  • Micro: Pseudohyphae invading tissue with neutrophilic infiltrate

2. ASPERGILLOSIS

  • Aspergillus fumigatus most common
  • Acute angle (45°) branching septate hyphae - GMS stain
  • Types:
    • Allergic bronchopulmonary aspergillosis (ABPA)
    • Aspergilloma (fungal ball in pre-existing cavity)
    • Invasive aspergillosis (in immunocompromised) - hemorrhagic infarcts (angioinvasive)

3. CRYPTOCOCCOSIS

  • Cryptococcus neoformans
  • India ink stain: thick mucoid capsule (clear halo)
  • PAS/Mucicarmine: magenta capsule
  • Soap bubble lesions in brain (gelatinous pseudocysts)
  • AIDS patients: meningoencephalitis

4. MUCORMYCOSIS (ZYGOMYCOSIS)

  • Rhizopus, Mucor spp.
  • Broad, non-septate hyphae branching at right angles (90°)
  • Angioinvasive → tissue infarction
  • Rhinocerebral form in diabetics (DKA)

5. HISTOPLASMOSIS

  • Histoplasma capsulatum
  • Intracellular within macrophages (2-4 μm yeast)
  • Endemic: Ohio/Mississippi river valleys
  • Mimics TB - granulomas, calcification

5. PRIMARY TUBERCULOSIS - Pathogenesis, Common Sites, Evolution of Tubercle, Primary Complex ⭐

Etiology

  • Mycobacterium tuberculosis (acid-fast bacillus)
  • Transmission: respiratory droplets (aerosol)
  • Primary TB: disease in previously unexposed, unsensitized individual
  • Only ~5% of newly infected develop significant disease

Pathogenesis

┌────────────────────────────────────────────────────────────────┐
│           PATHOGENESIS OF PRIMARY TUBERCULOSIS                 │
│                                                                │
│  INHALATION of M. tuberculosis                                 │
│       ↓                                                        │
│  Bacilli reach ALVEOLI (lower part of UPPER LOBE or            │
│                          upper part of LOWER LOBE)            │
│       ↓                                                        │
│  Phase 1 - INNATE RESPONSE (first 3 weeks):                    │
│  Alveolar macrophages phagocytose bacilli                       │
│  M. tb prevents phagolysosome fusion                           │
│  Bacilli survive & multiply INSIDE macrophages                 │
│  Macrophages release chemokines → monocyte recruitment         │
│  Dendritic cells carry antigens to DRAINING LYMPH NODES        │
│       ↓ (~3 weeks later)                                       │
│  Phase 2 - ADAPTIVE IMMUNITY (Th1 response):                   │
│  DCs present antigens → Th1 differentiation                    │
│  (requires IL-12, IL-18 from APCs)                             │
│       ↓                                                        │
│  Th1 cells produce IFN-γ                                       │
│       ↓                                                        │
│  IFN-γ activates macrophages:                                  │
│  1. Produces nitric oxide + ROS → kills bacteria               │
│  2. Mobilizes defensins (cathelicidin)                         │
│  3. Stimulates AUTOPHAGY                                       │
│       ↓                                                        │
│  Activated macrophages → EPITHELIOID HISTIOCYTES               │
│       ↓                                                        │
│  GRANULOMA FORMATION + CASEOUS NECROSIS                        │
│       ↓                                                        │
│  ~95%: Infection CONTAINED → Ghon complex heals                │
│   ~5%: Progressive primary TB (immunocompromised)              │
└────────────────────────────────────────────────────────────────┘

Role of TNF: Recruits monocytes, maintains granuloma integrity. TNF inhibitors (anti-rheumatic drugs) → reactivation of TB.


Common Sites of Primary TB

  1. Lungs (most common) - subpleural, lower part of upper lobe OR upper part of lower lobe
  2. Intestine (ileum) - from ingestion of M. bovis
  3. Tonsil / pharynx - rare
  4. Skin (primary inoculation TB)

Evolution of the Tubercle (Granuloma)

STAGE 1 - INITIAL LESION:
Local accumulation of macrophages (HISTIOCYTES)
       ↓
STAGE 2 - EPITHELIOID GRANULOMA:
Macrophages transform into EPITHELIOID CELLS
(elongated, pink cytoplasm, looks like epithelium but IS NOT)
Surrounded by LYMPHOCYTES (CD4+ T cells mainly)
       ↓
STAGE 3 - GIANT CELL FORMATION:
Epithelioid cells fuse → LANGHANS GIANT CELLS
(nuclei arranged in horseshoe/peripheral pattern)
       ↓
STAGE 4 - CASEOUS NECROSIS:
Centre becomes CASEOUS (cheese-like, amorphous, eosinophilic)
= due to hypersensitivity (DTH) reaction
Caseous necrosis = PATHOGNOMONIC of TB
       ↓
STAGE 5 - RESOLUTION / HEALING:
Fibrosis → Calcification (Ranke complex)
         OR
Liquefaction → Cavity formation (secondary TB)

Diagram of Tubercle:

          ┌─────────────────────────────────┐
          │   TB GRANULOMA (TUBERCLE)        │
          │                                 │
          │   ~~~~~~~~CASEOUS NECROSIS~~~~~~│ ← Centre
          │  ~    (amorphous, pink,    ~    │
          │  ~     cheese-like)        ~    │
          │   ~~~~~~~~~~~~~~~~~~~~~~~~      │
          │  [E][E][E][L][L][E][E][E]       │ ← Epithelioid cells (E)
          │  [L]  LANGHANS GIANT CELL [L]   │   Lymphocytes (L)
          │        ⊂ nuclei in               │
          │          horseshoe pattern ⊃     │
          │  [E][E][E][L][L][E][E][E]       │
          │ Fibrous capsule (outer rim)      │
          └─────────────────────────────────┘

Primary Complex - Components ⭐

The Primary (Ghon's) Complex = 3 components:
PRIMARY COMPLEX = GHON FOCUS + LYMPHANGITIS + LYMPHADENITIS

     1. GHON FOCUS (Parenchymal lesion)
     ────────────────────────────────────
     - 1-1.5 cm gray-white area of consolidation
     - Subpleural location
     - Lower part of upper lobe or upper part of lower lobe
     - Centre undergoes caseous necrosis
     - = THE PARENCHYMAL COMPONENT

     2. LYMPHANGITIS
     ────────────────
     - Inflammatory involvement of lymphatic channels
     - Between Ghon focus and hilar lymph nodes

     3. HILAR / REGIONAL LYMPHADENOPATHY
     ─────────────────────────────────────
     - Caseous enlargement of regional (hilar) lymph nodes
     - Usually MORE prominent than the parenchymal lesion
     - = THE NODAL COMPONENT

RANKE COMPLEX:

When the Ghon complex undergoes fibrosis + calcification = Ranke complex (visible on chest X-ray)

6. GHON'S COMPLEX - Gross, Microscopic & Fate ⭐⭐⭐

Definition

The combination of the Ghon focus (parenchymal lesion) + caseous hilar lymph node enlargement + the lymphangitis connecting them = Ghon's Complex

Gross Features

GROSS FEATURES OF GHON'S COMPLEX:
─────────────────────────────────────────────────────
GHON FOCUS:
● Location: Subpleural; lower part of upper lobe OR
            upper part of lower lobe (close to pleura)
● Size: 1 to 1.5 cm
● Colour: Gray-white area of consolidation
● Centre: Caseous necrosis (yellow-white, cheese-like material)
● Surface: May show pleural adhesions
● Surrounding: Zone of consolidation

HILAR LYMPH NODES:
● Enlarged, discrete or matted lymph nodes at hilum
● Cut section: Yellow-white caseous material
● Nodes often LARGER than the parenchymal focus
● May show periadenitis / matting together

LYMPHATICS:
● Thickened lymphatic channels visible on gross
● "Beaded" appearance between focus and nodes
─────────────────────────────────────────────────────

Microscopic Features

MICROSCOPIC FEATURES:
─────────────────────────────────────────────────────
At the GHON FOCUS (parenchymal lesion):

1. CASEOUS NECROSIS at centre:
   - Amorphous, granular, eosinophilic material
   - "Ghost" cell outlines may be visible
   - Loses all cellular architecture

2. GRANULOMATOUS INFLAMMATION surrounding it:
   - EPITHELIOID CELLS (activated macrophages)
     - Elongated cells with eosinophilic, granular cytoplasm
     - Blunt-ended, "footprint-shaped" nuclei
   - LANGHANS GIANT CELLS
     - Peripheral / horseshoe arrangement of nuclei
   - LYMPHOCYTES (mainly CD4+ T cells) at periphery
   - Occasional plasma cells

3. FIBROUS CAPSULE:
   - Outer rim of fibrous tissue encapsulating the granuloma

4. AFB STAIN (Ziehl-Neelsen):
   - Red acid-fast bacilli (may be scanty in primary TB)
   - More abundant in progressive disease / immunocompromised

In HILAR LYMPH NODES:
   - Similar caseating granulomas
   - Effacement of nodal architecture
   - Caseous necrosis (may be more extensive than focus)

IMPORTANT: In immunocompromised (HIV, CD4 < 200):
   - Granulomas ABSENT
   - Sheets of macrophages with numerous bacilli
   - No caseous necrosis typical pattern
─────────────────────────────────────────────────────

Fate of Ghon's Complex ⭐⭐⭐

┌─────────────────────────────────────────────────────────────────┐
│                    FATE OF GHON'S COMPLEX                       │
│                                                                 │
│         GHON'S COMPLEX (primary TB lesion)                      │
│                      │                                          │
│          ┌───────────┴────────────┐                             │
│    95% of cases                5% of cases                      │
│    (healthy, normal            (immunocompromised,              │
│     immunity)                   malnourished, children)         │
│          │                           │                          │
│          ↓                           ↓                          │
│    HEALING / RESOLUTION       PROGRESSIVE PRIMARY TB            │
│          │                                                      │
│    ┌─────┴──────┐                                               │
│    ↓            ↓                                               │
│ FIBROSIS    CALCIFICATION                                       │
│             ↓                                                   │
│          RANKE COMPLEX                                          │
│      (fibrosis + calcification                                  │
│       - seen on chest X-ray)                                    │
│                                                                 │
│  IF IMMUNITY WANES LATER:                                       │
│  REACTIVATION → SECONDARY TB                                    │
│  (apical lesion, cavity formation)                              │
│                                                                 │
│  COMPLICATIONS OF PRIMARY TB:                                   │
│  1. Haematogenous spread → Miliary TB                           │
│  2. Lymphatic spread → Meningitis, TB vertebra                  │
│  3. Caseous lymph node ruptures → bronchopneumonia              │
│  4. Pleural effusion                                            │
│  5. Progressive primary TB in immunocompromised                 │
└─────────────────────────────────────────────────────────────────┘

Summary Table - Fate

OutcomeMechanismResult
Resolution (95%)Immune controlFibrosis → Calcification = Ranke complex
Progressive Primary (5%)Immune failureCaseous pneumonia, miliary TB
Reactivation (later)Waning immunitySecondary/post-primary TB (apical cavity)
Miliary TBHaematogenous spreadMillet-seed foci throughout organs
TB MeningitisHaematogenous/lymphaticCNS involvement

Quick Comparison Summary

FeatureGhon FocusGhon ComplexRanke Complex
DefinitionParenchymal lesion onlyFocus + Lymphangitis + NodeCalcified Ghon complex
LocationSubpleural, lower upper lobeLung + hilumSame sites, calcified
Size1-1.5 cmExtendedSmaller (healed)
HistologyCaseating granulomaCaseating granulomas at multiple sitesCalcified fibrous tissue
X-rayNot visibleNot visibleVisible as calcified nodule

Sources: Robbins, Cotran & Kumar - Pathologic Basis of Disease, 10e (9780443264528) and Robbins & Kumar Basic Pathology (9780323790185)

MUHS EXAM TIPS:

  • Ghon complex fate is asked almost every exam - memorize the 5 fates
  • Leprosy - always compare tuberculoid vs lepromatous in a table
  • Lepra cell and Langhans giant cell diagrams are frequently asked to draw
  • Malaria - know PfEMP1, sequestration, and cerebral malaria mechanism
  • Cysticercosis - distinguish between human as intermediate vs definitive host
  • Tubercle evolution - 5 stages, Langhans giant cell nucleus pattern (horseshoe/peripheral)
  • Primary complex components = Ghon focus + Lymphangitis + Hilar adenopathy (3-component answer)

Generate a comprehensive revision PDF with all tables, diagrams & mnemonics for these 6 topics

Reading File
Running Command

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

Writing File

~/muhs-study-guide/generate_pdf.py

#!/usr/bin/env python3
"""
MUHS 2nd MBBS Pathology - Comprehensive Revision PDF
Topics: Malaria, Cysticercosis, Leprosy, Viral/Fungal Infections,
        Primary TB, Ghon's Complex
Based on Robbins & Kumar Pathology
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.platypus.flowables import Flowable
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.pdfgen import canvas
from reportlab.graphics.shapes import Drawing, Rect, String, Line, Circle, Polygon
from reportlab.graphics import renderPDF
import os

OUTPUT_PATH = "/home/daytona/workspace/muhs-study-guide/MUHS_Pathology_Revision.pdf"

# ── COLOUR PALETTE ────────────────────────────────────────────────────────────
C_DARK_BLUE   = colors.HexColor("#1a3a5c")
C_MED_BLUE    = colors.HexColor("#2563a8")
C_LIGHT_BLUE  = colors.HexColor("#dbeafe")
C_TEAL        = colors.HexColor("#0f766e")
C_LIGHT_TEAL  = colors.HexColor("#ccfbf1")
C_RED         = colors.HexColor("#b91c1c")
C_LIGHT_RED   = colors.HexColor("#fee2e2")
C_ORANGE      = colors.HexColor("#c2410c")
C_LIGHT_ORANGE= colors.HexColor("#ffedd5")
C_GREEN       = colors.HexColor("#166534")
C_LIGHT_GREEN = colors.HexColor("#dcfce7")
C_PURPLE      = colors.HexColor("#6b21a8")
C_LIGHT_PURPLE= colors.HexColor("#f3e8ff")
C_YELLOW      = colors.HexColor("#854d0e")
C_LIGHT_YELLOW= colors.HexColor("#fef9c3")
C_DARK_GREY   = colors.HexColor("#374151")
C_MID_GREY    = colors.HexColor("#6b7280")
C_LIGHT_GREY  = colors.HexColor("#f3f4f6")
C_WHITE       = colors.white
C_BLACK       = colors.black

# ── STYLES ────────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

def make_style(name, parent='Normal', **kwargs):
    return ParagraphStyle(name, parent=styles[parent], **kwargs)

# Cover / section heading
S_COVER_TITLE = make_style('CoverTitle',
    fontSize=28, textColor=C_WHITE, alignment=TA_CENTER,
    fontName='Helvetica-Bold', spaceAfter=8)

S_COVER_SUB = make_style('CoverSub',
    fontSize=14, textColor=colors.HexColor("#bfdbfe"),
    alignment=TA_CENTER, fontName='Helvetica', spaceAfter=6)

S_SECTION = make_style('Section',
    fontSize=16, textColor=C_WHITE, fontName='Helvetica-Bold',
    alignment=TA_LEFT, spaceAfter=6, spaceBefore=4)

S_SUBSECTION = make_style('Subsection',
    fontSize=12, textColor=C_DARK_BLUE, fontName='Helvetica-Bold',
    spaceAfter=4, spaceBefore=8)

S_BODY = make_style('Body',
    fontSize=9.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=14, spaceAfter=4, alignment=TA_JUSTIFY)

S_BULLET = make_style('Bullet',
    fontSize=9.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=13, spaceAfter=2, leftIndent=14,
    bulletIndent=4)

S_BULLET2 = make_style('Bullet2',
    fontSize=9, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=12, spaceAfter=1, leftIndent=28, bulletIndent=18)

S_MONO = make_style('Mono',
    fontSize=8.5, textColor=C_DARK_GREY, fontName='Courier',
    leading=12, spaceAfter=2, leftIndent=6)

S_MNEMONIC = make_style('Mnemonic',
    fontSize=10.5, textColor=C_TEAL, fontName='Helvetica-Bold',
    leading=14, spaceAfter=3, alignment=TA_CENTER)

S_KEY = make_style('Key',
    fontSize=9, textColor=C_RED, fontName='Helvetica-Bold',
    leading=13, spaceAfter=2)

S_CAPTION = make_style('Caption',
    fontSize=8, textColor=C_MID_GREY, fontName='Helvetica-Oblique',
    alignment=TA_CENTER, spaceAfter=4)

S_TABLE_HEADER = make_style('TblHdr',
    fontSize=9, textColor=C_WHITE, fontName='Helvetica-Bold',
    alignment=TA_CENTER)

S_TABLE_CELL = make_style('TblCell',
    fontSize=8.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=12, alignment=TA_LEFT)

S_TABLE_CELL_C = make_style('TblCellC',
    fontSize=8.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=12, alignment=TA_CENTER)

S_SMALL = make_style('Small',
    fontSize=8, textColor=C_MID_GREY, fontName='Helvetica',
    leading=11, spaceAfter=2)

# ── HELPER FLOWABLES ─────────────────────────────────────────────────────────

class ColorBox(Flowable):
    """A rounded-rectangle coloured banner."""
    def __init__(self, text, bg_color, text_color=colors.white,
                 width=None, height=28, font_size=13, bold=True):
        Flowable.__init__(self)
        self.text = text
        self.bg_color = bg_color
        self.text_color = text_color
        self.width = width or (A4[0] - 4*cm)
        self.height = height
        self.font_size = font_size
        self.bold = bold

    def wrap(self, availW, availH):
        self.width = min(self.width, availW)
        return self.width, self.height

    def draw(self):
        c = self.canv
        c.setFillColor(self.bg_color)
        c.roundRect(0, 0, self.width, self.height, 6, fill=1, stroke=0)
        c.setFillColor(self.text_color)
        fn = 'Helvetica-Bold' if self.bold else 'Helvetica'
        c.setFont(fn, self.font_size)
        c.drawCentredString(self.width/2, self.height/2 - self.font_size/2 + 2, self.text)


class DiagramBox(Flowable):
    """Pre-drawn ASCII-art style box using ReportLab lines."""
    def __init__(self, lines, bg=C_LIGHT_GREY, border=C_MED_BLUE,
                 width=None, font_size=8):
        Flowable.__init__(self)
        self.lines = lines
        self.bg = bg
        self.border = border
        self._width = width
        self.font_size = font_size
        self.line_height = font_size + 3
        self.padding = 8

    def wrap(self, availW, availH):
        self._width = self._width or availW
        h = len(self.lines) * self.line_height + 2 * self.padding
        return self._width, h

    def draw(self):
        c = self.canv
        h = len(self.lines) * self.line_height + 2 * self.padding
        c.setFillColor(self.bg)
        c.setStrokeColor(self.border)
        c.setLineWidth(1)
        c.roundRect(0, 0, self._width, h, 5, fill=1, stroke=1)
        c.setFont('Courier', self.font_size)
        c.setFillColor(C_DARK_GREY)
        y = h - self.padding - self.font_size
        for line in self.lines:
            c.drawString(self.padding, y, line)
            y -= self.line_height


def section_banner(title, topic_num, color=C_DARK_BLUE):
    """Returns a list of flowables forming a section header."""
    return [
        Spacer(1, 0.3*cm),
        ColorBox(f"TOPIC {topic_num}  |  {title}", bg_color=color, font_size=13),
        Spacer(1, 0.2*cm),
    ]


def subsection(title, color=C_MED_BLUE):
    return [
        Spacer(1, 0.15*cm),
        ColorBox(title, bg_color=color, height=22, font_size=10.5, text_color=C_WHITE),
        Spacer(1, 0.1*cm),
    ]


def mnemonic_box(title, items, bg=C_LIGHT_TEAL, border=C_TEAL):
    """A nicely styled mnemonic box."""
    content = [
        [Paragraph(f"<b>🧠 MNEMONIC: {title}</b>", make_style('Mn2',
            fontSize=10, textColor=C_TEAL, fontName='Helvetica-Bold',
            alignment=TA_CENTER))],
    ]
    for item in items:
        content.append([Paragraph(item, make_style('Mn3',
            fontSize=9.5, textColor=C_TEAL, fontName='Helvetica',
            alignment=TA_CENTER, leading=13))])
    t = Table(content, colWidths=[A4[0] - 4*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), bg),
        ('BOX', (0,0), (-1,-1), 1.5, border),
        ('ROUNDEDCORNERS', [6]),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
        ('RIGHTPADDING', (0,0), (-1,-1), 10),
    ]))
    return [t, Spacer(1, 0.2*cm)]


def comparison_table(headers, rows, col_widths=None, header_bg=C_DARK_BLUE):
    """Styled comparison table."""
    header_row = [Paragraph(h, S_TABLE_HEADER) for h in headers]
    table_data = [header_row]
    for r in rows:
        table_data.append([Paragraph(str(c), S_TABLE_CELL) for c in r])
    if col_widths is None:
        n = len(headers)
        col_widths = [(A4[0] - 4*cm) / n] * n
    t = Table(table_data, colWidths=col_widths, repeatRows=1)
    style = [
        ('BACKGROUND', (0,0), (-1,0), header_bg),
        ('TEXTCOLOR', (0,0), (-1,0), C_WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,0), 9),
        ('ALIGN', (0,0), (-1,-1), 'LEFT'),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [C_WHITE, C_LIGHT_GREY]),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#d1d5db")),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
    ]
    t.setStyle(TableStyle(style))
    return [t, Spacer(1, 0.25*cm)]


def key_fact(text):
    return Paragraph(f"<b>★ KEY FACT:</b> {text}", S_KEY)


def bp(text, indent=0):
    """Bullet paragraph."""
    prefix = "• "
    style = S_BULLET if indent == 0 else S_BULLET2
    return Paragraph(f"{prefix}{text}", style)


def divider(color=C_MED_BLUE):
    return HRFlowable(width="100%", thickness=1, color=color,
                      spaceAfter=4, spaceBefore=4)


# ── PAGE TEMPLATE ─────────────────────────────────────────────────────────────

def on_first_page(canvas, doc):
    canvas.saveState()
    # Full-page gradient background
    canvas.setFillColor(C_DARK_BLUE)
    canvas.rect(0, 0, A4[0], A4[1], fill=1, stroke=0)
    # Decorative band at top
    canvas.setFillColor(C_MED_BLUE)
    canvas.rect(0, A4[1]-80, A4[0], 80, fill=1, stroke=0)
    # Decorative band at bottom
    canvas.setFillColor(C_TEAL)
    canvas.rect(0, 0, A4[0], 40, fill=1, stroke=0)
    canvas.restoreState()


def on_later_pages(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(C_DARK_BLUE)
    canvas.rect(0, A4[1]-25, A4[0], 25, fill=1, stroke=0)
    canvas.setFillColor(C_WHITE)
    canvas.setFont('Helvetica-Bold', 8)
    canvas.drawString(1.5*cm, A4[1]-16, "MUHS 2nd MBBS PATHOLOGY — RAPID REVISION")
    canvas.setFont('Helvetica', 8)
    canvas.drawRightString(A4[0]-1.5*cm, A4[1]-16, "Robbins & Kumar Pathology")
    # Footer
    canvas.setFillColor(C_DARK_BLUE)
    canvas.rect(0, 0, A4[0], 18, fill=1, stroke=0)
    canvas.setFillColor(C_WHITE)
    canvas.setFont('Helvetica', 7.5)
    canvas.drawCentredString(A4[0]/2, 5, f"Page {doc.page}")
    canvas.restoreState()


# ── BUILD CONTENT ─────────────────────────────────────────────────────────────

def build_cover():
    elements = []
    # Large vertical spacer to push content to middle of page
    elements.append(Spacer(1, 5.5*cm))
    # Title
    cover_title_style = make_style('CTMain',
        fontSize=30, textColor=C_WHITE, fontName='Helvetica-Bold',
        alignment=TA_CENTER, spaceAfter=10)
    elements.append(Paragraph("MUHS 2nd MBBS PATHOLOGY", cover_title_style))
    elements.append(Paragraph("COMPREHENSIVE RAPID REVISION", make_style('CT2',
        fontSize=20, textColor=colors.HexColor("#93c5fd"),
        fontName='Helvetica-Bold', alignment=TA_CENTER, spaceAfter=16)))
    elements.append(HRFlowable(width="70%", thickness=2,
                               color=C_TEAL, spaceAfter=16, hAlign='CENTER'))
    # Topics
    topic_style = make_style('CTopic',
        fontSize=11.5, textColor=colors.HexColor("#e0f2fe"),
        fontName='Helvetica', alignment=TA_CENTER, spaceAfter=6, leading=18)
    topics = [
        "1. Malaria – Pathogenesis &amp; Morphology",
        "2. Cysticercosis – Etiopathogenesis &amp; Morphology",
        "3. Leprosy – Pathogenesis, Classification &amp; Findings  ★★★",
        "4. Common Viral &amp; Fungal Infections",
        "5. Primary Tuberculosis – Pathogenesis, Sites &amp; Primary Complex  ★",
        "6. Ghon's Complex – Gross, Microscopic &amp; Fate  ★★★",
    ]
    for t in topics:
        elements.append(Paragraph(t, topic_style))
    elements.append(Spacer(1, 1*cm))
    elements.append(HRFlowable(width="70%", thickness=2,
                               color=C_TEAL, spaceAfter=12, hAlign='CENTER'))
    elements.append(Paragraph("Based on Robbins, Cotran &amp; Kumar — Pathologic Basis of Disease (10e)",
        make_style('CRef', fontSize=9, textColor=colors.HexColor("#bfdbfe"),
                   fontName='Helvetica-Oblique', alignment=TA_CENTER)))
    elements.append(PageBreak())
    return elements


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 1 — MALARIA
# ────────────────────────────────────────────────────────────────────────────
def build_malaria():
    E = []
    E += section_banner("MALARIA", 1, C_RED)

    # Overview box
    overview_lines = [
        "Causative organisms: Plasmodium falciparum (most virulent), P. vivax, P. ovale, P. malariae, P. knowlesi",
        "Vector: Female Anopheles mosquito  |  Reservoir: Humans only",
        "200+ million cases/year worldwide  |  600,000+ deaths/year (mostly children < 5 yrs in Africa)",
    ]
    for l in overview_lines:
        E.append(Paragraph(l, S_BODY))
    E.append(Spacer(1, 0.2*cm))

    # Pathogenesis heading
    E += subsection("PATHOGENESIS — Life Cycle", C_MED_BLUE)

    life_cycle = [
        "  MOSQUITO BITE → Sporozoites enter blood",
        "        ↓",
        "  LIVER (Exo-erythrocytic stage) — ASYMPTOMATIC",
        "  Sporozoites bind hepatocytes (thrombospondin + circumsporozoite protein)",
        "  Sporozoites → Merozoites (up to 30,000 per hepatocyte)",
        "  [P. vivax / P. ovale → form HYPNOZOITES → relapse weeks-months later]",
        "        ↓",
        "  Hepatocytes rupture → Merozoites released into blood",
        "        ↓",
        "  RBC INVASION (Erythrocytic stage) — SYMPTOMATIC",
        "  Merozoites bind sialic acid on glycophorin on RBC surface",
        "  Merozoite → Trophozoite → Schizont → new Merozoites",
        "  P. falciparum: PfEMP1 knobs appear on RBC surface",
        "  RBC LYSIS → merozoites released → fever, chills, rigors (TNF surge)",
        "        ↓",
        "  Some trophozoites → GAMETOCYTES (sexual forms)",
        "  Mosquito ingests gametocytes → restarts cycle",
    ]
    E.append(DiagramBox(life_cycle, bg=C_LIGHT_RED, border=C_RED))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("WHY P. FALCIPARUM IS MORE VIRULENT", C_RED)
    virulence = [
        ("1. Infects ALL ages of RBCs", "Causes high-level parasitemia (vs. only young/old RBCs for other spp.)"),
        ("2. PfEMP1 on RBC surface knobs", "Binds ICAM-1, VCAM-1, CD36, E-selectin on endothelium → SEQUESTRATION in capillaries → blocks blood flow → cerebral malaria"),
        ("3. Rosette formation", "Infected RBCs clump together, worsening blockage"),
        ("4. No hypnozoites", "No relapse, but high acute parasitemia"),
        ("5. Antigenic variation", "Switches PfEMP1 variants each generation → escapes antibody response"),
    ]
    E += comparison_table(["Mechanism", "Effect"],
                          virulence,
                          col_widths=[4.5*cm, 10*cm],
                          header_bg=C_RED)

    E += subsection("FEVER PERIODICITY", C_ORANGE)
    fever_data = [
        ("P. vivax / P. ovale", "Every 48 hours", "Benign tertian malaria"),
        ("P. malariae", "Every 72 hours", "Quartan malaria"),
        ("P. falciparum", "Irregular / every 36-48h", "Malignant tertian malaria (most dangerous)"),
        ("P. knowlesi", "Every 24 hours", "Quotidian / potentially severe"),
    ]
    E += comparison_table(["Species", "Periodicity", "Type"],
                          fever_data, header_bg=C_ORANGE)

    E += subsection("MORPHOLOGY — Organ Changes", C_MED_BLUE)
    morphology_data = [
        ("SPLEEN", "Splenomegaly (may exceed 1000g), gray-black hemozoin pigment, red pulp congestion+hyperplasia; chronic → fibrotic, brittle, thick capsule"),
        ("LIVER", "Enlarged, pigmented; Kupffer cells laden with malarial pigment, parasitized RBCs, cellular debris"),
        ("BRAIN\n(P. falciparum)", "Vessels PLUGGED with parasitized RBCs; ring hemorrhages; Dürck granuloma (malarial granuloma); neuronal degeneration; focal ischemic softening"),
        ("KIDNEY", "Enlarged, congested; malarial pigment in glomeruli; hemoglobin casts in tubules (Blackwater fever = massive hemolysis + hemoglobinuria)"),
        ("BONE MARROW / LYMPH NODES", "Pigmented phagocytic cells; hemozoin pigment throughout"),
        ("BLOOD SMEAR\n(Diagnostic)", "Giemsa stain: ring trophozoites, schizonts, gametocytes inside RBCs. Ring forms with double chromatin dot = P. falciparum"),
    ]
    E += comparison_table(["Organ", "Findings"],
                          morphology_data,
                          col_widths=[3.5*cm, 11*cm],
                          header_bg=C_MED_BLUE)

    E += mnemonic_box("Plasmodium species",
        ["'Fever Very Often Makes People Sick'",
         "F = Falciparum  |  V = Vivax  |  O = Ovale  |  M = Malariae  |  P = P. knowlesi  |  S = Sporozoite entry"],
        bg=C_LIGHT_RED, border=C_RED)

    E += mnemonic_box("P. falciparum virulence — 'SCAR'",
        ["S = Sequestration (PfEMP1 binds endothelium)",
         "C = Can infect all age RBCs",
         "A = Antigenic variation (escapes immunity)",
         "R = Rosette formation"],
        bg=C_LIGHT_ORANGE, border=C_ORANGE)

    E.append(key_fact("Diagnostic test = Giemsa-stained peripheral blood smear. Dürck granuloma = pathognomonic of cerebral malaria."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 2 — CYSTICERCOSIS
# ────────────────────────────────────────────────────────────────────────────
def build_cysticercosis():
    E = []
    E += section_banner("CYSTICERCOSIS", 2, C_PURPLE)

    E.append(Paragraph(
        "<b>Definition:</b> Disease caused by <b>larvae (cysticercus)</b> of <i>Taenia solium</i> "
        "(pork tapeworm) when HUMANS act as the <b>INTERMEDIATE HOST</b>.", S_BODY))
    E.append(Spacer(1, 0.15*cm))

    host_data = [
        ("NORMAL life cycle", "Pig = Intermediate host (harbors cysticercus)\nHuman = Definitive host (harbors adult tapeworm in intestine)"),
        ("CYSTICERCOSIS", "HUMAN = Intermediate host (ingests eggs, develops cysticerci in tissues)"),
    ]
    E += comparison_table(["Condition", "Host Role"], host_data,
                          col_widths=[4.5*cm, 10*cm], header_bg=C_PURPLE)

    E += subsection("ETIOPATHOGENESIS", C_PURPLE)
    patho = [
        "  Human ingests T. solium EGGS (contaminated food/water/fecal-oral route)",
        "        ↓",
        "  Eggs hatch in intestine → ONCOSPHERES (hexacanth embryos with 6 hooklets)",
        "        ↓",
        "  Oncospheres penetrate intestinal wall → enter bloodstream",
        "        ↓",
        "  Haematogenous dissemination to TISSUES",
        "        ↓",
        "  Develop into CYSTICERCI (fluid-filled cysts with invaginated scolex)",
        "        ↓",
        "  PREFERRED SITES: Brain, Subcutaneous tissue, Eye, Skeletal muscle, Heart, Liver",
        "        ↓",
        "  ALIVE CYST → minimal inflammation (immune evasion by cyst)",
        "  DYING/DEAD CYST → intense inflammatory response → granuloma → calcification",
    ]
    E.append(DiagramBox(patho, bg=C_LIGHT_PURPLE, border=C_PURPLE))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("CLINICAL FEATURES BY SITE", C_MED_BLUE)
    clinical = [
        ("Neurocysticercosis (NCC)", "Most dangerous; seizures (most common cause of acquired epilepsy in endemic areas), headache, raised ICP, hydrocephalus, focal neurological deficits"),
        ("Ocular cysticercosis", "Floaters, visual disturbances, blindness (subretinal/vitreous cyst)"),
        ("Subcutaneous", "Palpable, non-tender nodules; calcify on X-ray"),
        ("Muscular", "Pseudohypertrophy of muscles; calcified cysts on imaging"),
    ]
    E += comparison_table(["Site", "Manifestations"], clinical,
                          col_widths=[4*cm, 10.5*cm], header_bg=C_MED_BLUE)

    E += subsection("MORPHOLOGY", C_PURPLE)
    E.append(Paragraph("<b>GROSS FEATURES:</b>", S_SUBSECTION))
    gross = [
        "Round/oval translucent fluid-filled cyst, 0.5–2 cm (up to 20 cm in racemose form)",
        "White, glistening wall; SCOLEX visible as white nodule inside",
        "RACEMOSE variant: grapelike cluster, no scolex, found in cisterns/ventricles of brain",
        "Calcified cysts visible on plain X-ray as 'puffed rice' calcifications (in muscles)",
    ]
    for g in gross:
        E.append(bp(g))

    E.append(Spacer(1, 0.15*cm))
    E.append(Paragraph("<b>MICROSCOPIC FEATURES (3 stages):</b>", S_SUBSECTION))
    micro_data = [
        ("VIABLE CYST", "Outer cuticular layer (lamellar, eosinophilic)\nMiddle cellular (reticular) layer\nInner germinal layer\nScolex with suckers and hooklets visible\nMinimal host inflammatory response"),
        ("DEGENERATING/\nDEAD CYST", "Cyst wall hyalinizes and breaks down\nINTENSE INFLAMMATION:\n• Eosinophils, neutrophils, lymphocytes\n• Plasma cells, macrophages\nGranuloma formation with giant cells"),
        ("CALCIFIED CYST\n(Healed)", "Dense calcification of dead scolex and wall\nFibrosis/gliosis surrounding (in brain)\n'Ghost' of cyst remains"),
    ]
    E += comparison_table(["Stage", "Microscopic Features"], micro_data,
                          col_widths=[4*cm, 10.5*cm], header_bg=C_PURPLE)

    E += mnemonic_box("Cysticercosis — 'CHEST'",
        ["C = Cyst (fluid-filled, with scolex)",
         "H = Hooklets on scolex (6 hooklets in oncosphere)",
         "E = Eggs ingested (fecal-oral route)",
         "S = Seizures (most common presentation — NCC)",
         "T = Taenia solium (pork tapeworm)"],
        bg=C_LIGHT_PURPLE, border=C_PURPLE)

    E.append(key_fact("Neurocysticercosis = most common cause of acquired epilepsy in developing countries. Diagnosis: CT/MRI + serology (EITB). Treatment: Albendazole + steroids."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 3 — LEPROSY ★★★
# ────────────────────────────────────────────────────────────────────────────
def build_leprosy():
    E = []
    E += section_banner("LEPROSY (Hansen Disease)  ★★★", 3, C_TEAL)

    E.append(Paragraph(
        "<b>Causative organism:</b> <i>Mycobacterium leprae</i> (and rarely M. lepromatosis). "
        "Slow progressive infection affecting <b>SKIN and PERIPHERAL NERVES</b>. "
        "Cannot be cultured in vitro. Proliferates best at <b>32–34°C</b> (cool tissues). "
        "Transmission via <b>human respiratory secretions</b>.", S_BODY))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("PATHOGENESIS", C_TEAL)
    patho = [
        "  M. leprae enters via respiratory tract",
        "        ↓",
        "  Taken up by DERMAL MACROPHAGES",
        "        ↓",
        "  Disseminates via blood → replicates in COOL TISSUES (skin, extremities, peripheral nerves)",
        "  PGL-1 lipid: invasion of host cells   |   Inhibits mitochondrial energy metabolism",
        "        ↓",
        "       HOST IMMUNE RESPONSE determines disease pattern:",
        "        ↙                                            ↘",
        "   STRONG Th1                                   WEAK Th1",
        "  (IL-2, IFN-γ, Th17)                       (Th2/Reg-T dominant)",
        "        ↓                                            ↓",
        "  TUBERCULOID LEPROSY                       LEPROMATOUS LEPROSY",
        "  (Paucibacillary)                          (Multibacillary)",
        "  Granulomas present                        No granulomas",
        "  Low bacterial load                        High bacterial load",
        "  Nerve destruction dominant                Diffuse skin/nerve invasion",
    ]
    E.append(DiagramBox(patho, bg=C_LIGHT_TEAL, border=C_TEAL))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("CLASSIFICATION", C_TEAL)
    E.append(Paragraph("<b>Ridley-Jopling Classification (Spectrum):</b>", S_SUBSECTION))
    spectrum_lines = [
        "  TUBERCULOID (TT) ←── BT ──── BB ──── BL ───→ LEPROMATOUS (LL)",
        "  |←────────── STRONG IMMUNITY ──────── WEAK IMMUNITY ──────────→|",
        "  |←───────── PAUCIBACILLARY ──────── MULTIBACILLARY ───────────→|",
        "  |←──── FEW SKIN LESIONS ────────── MANY SKIN LESIONS ─────────→|",
    ]
    E.append(DiagramBox(spectrum_lines, bg=C_LIGHT_TEAL, border=C_TEAL))
    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>WHO Classification (Clinical Use):</b>", S_SUBSECTION))
    who_data = [
        ("Paucibacillary (PB)", "1–5 skin lesions", "Tuberculoid / Borderline-T", "MDT 6 months"),
        ("Multibacillary (MB)", ">5 skin lesions", "Lepromatous / Borderline-L", "MDT 12 months"),
    ]
    E += comparison_table(["WHO Type", "Skin Lesions", "Ridley-Jopling", "MDT Duration"],
                          who_data, header_bg=C_TEAL)

    E += subsection("IMMUNOLOGY COMPARISON", C_MED_BLUE)
    immune_data = [
        ("T-cell response", "Strong Th1 (IFN-γ, IL-2)", "Weak Th1 / Th2 dominant"),
        ("Bacterial load", "Low (paucibacillary)", "High (multibacillary)"),
        ("Granulomas", "Well-formed, like TB", "Absent — lepra cells instead"),
        ("Antibodies", "Low", "High (but NOT protective — may cause vasculitis)"),
        ("Cell-mediated immunity", "Intact", "Deficient"),
        ("Lepromin test", "POSITIVE", "NEGATIVE"),
        ("Nerve involvement", "Asymmetric, destructive", "Symmetric, less inflamed"),
        ("Skin lesions", "Few, hypopigmented, anesthetic", "Multiple, nodular, leonine"),
    ]
    E += comparison_table(["Feature", "Tuberculoid", "Lepromatous"],
                          immune_data,
                          col_widths=[4.5*cm, 5.5*cm, 4.5*cm],
                          header_bg=C_MED_BLUE)

    E += subsection("GROSS (CLINICAL) FINDINGS", C_TEAL)
    E.append(Paragraph("<b>Tuberculoid Leprosy:</b>", S_KEY))
    tub_clinical = [
        "Flat red lesions → enlarge with indurated, elevated, hyperpigmented margins + depressed pale centres (central healing)",
        "ASYMMETRIC large peripheral nerve involvement (ulnar, radial, peroneal, great auricular)",
        "Skin ANESTHESIA (destroyed nerves)",
        "Muscle atrophy, contractures, chronic ulcers, autoamputation of digits",
        "Facial nerve palsy → eyelid paralysis → keratitis, corneal ulcers",
    ]
    for t in tub_clinical:
        E.append(bp(t))

    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>Lepromatous Leprosy:</b>", S_KEY))
    lep_clinical = [
        "SYMMETRIC skin thickening; macular, papular, or NODULAR lesions on face, ears, wrists, elbows, knees",
        "Nodules coalesce → LEONINE FACIES (lion-like face)",
        "Saddle-nose deformity (nasal bone destruction)",
        "Hyposthetic / anesthetic skin lesions",
        "Bacilli-laden nasal discharge",
        "Testes: extensive involvement → destruction of seminiferous tubules → sterility + gynecomastia",
        "Symmetric nerve invasion (ulnar, peroneal) with minimal inflammation",
    ]
    for l in lep_clinical:
        E.append(bp(l))

    E += subsection("MICROSCOPIC FINDINGS", C_TEAL)
    micro_data = [
        ("TUBERCULOID", "Well-formed GRANULOMAS (like TB)\nEpithelioid cells + Langhans giant cells\nDense lymphocytic infiltrate\nGranulomas enclose & DESTROY NERVES\nBacilli ABSENT / very rare (AFB -ve)\nName = PAUCIBACILLARY"),
        ("LEPROMATOUS", "Large aggregates of LIPID-LADEN MACROPHAGES = LEPRA CELLS (Virchow cells)\nLepra cells packed with GLOBI (masses of AFB)\nGlobi look like 'cigar bundles' on AFB stain\nNO granulomas (CMI absent)\nGRENZ ZONE (clear subepidermal zone)\nBacilli abundant — MULTIBACILLARY\nTestes: destruction of seminiferous tubules"),
    ]
    E += comparison_table(["Type", "Microscopic Features"], micro_data,
                          col_widths=[3.5*cm, 11*cm], header_bg=C_TEAL)

    # Lepra cell diagram
    lepra_cell = [
        "          LEPRA CELL DIAGRAM (Lepromatous Leprosy)",
        "    ┌─────────────────────────────────────────────┐",
        "    │          MACROPHAGE (Virchow Cell)           │",
        "    │                                             │",
        "    │   [====AFB====]  [====AFB====]  [==AFB==]   │",
        "    │      GLOBUS 1       GLOBUS 2     GLOBUS 3   │",
        "    │    (masses of acid-fast bacilli in bundles) │",
        "    │                                             │",
        "    │          FOAMY CYTOPLASM (lipid-filled)      │",
        "    │                  [ NUCLEUS ]                │",
        "    └─────────────────────────────────────────────┘",
        "    Stain: Ziehl-Neelsen (AFB) — red bacilli on blue bg",
    ]
    E.append(DiagramBox(lepra_cell, bg=C_LIGHT_TEAL, border=C_TEAL))
    E.append(Spacer(1, 0.15*cm))

    # Langhans giant cell diagram
    lang_cell = [
        "     LANGHANS GIANT CELL DIAGRAM (Tuberculoid / TB)",
        "    ┌──────────────────────────────────────────────┐",
        "    │                                              │",
        "    │         O  O  O  O  O                        │",
        "    │      O                    O                  │",
        "    │                                              │",
        "    │        LARGE PINK CYTOPLASM                  │",
        "    │      (fused epithelioid cells)               │",
        "    │                                              │",
        "    │      O                    O                  │",
        "    │         O  O  O  O  O                        │",
        "    │   Nuclei arranged in HORSESHOE / PERIPHERAL  │",
        "    │             PATTERN (key feature)            │",
        "    └──────────────────────────────────────────────┘",
    ]
    E.append(DiagramBox(lang_cell, bg=C_LIGHT_BLUE, border=C_MED_BLUE))
    E.append(Spacer(1, 0.15*cm))

    E += mnemonic_box("Types of Leprosy — 'TT BB LL (Two Ts, Two Bs, Two Ls)'",
        ["TT = Tuberculoid (one extreme)",
         "BB = Borderline (middle)",
         "LL = Lepromatous (other extreme)",
         "BT = Borderline Tuberculoid  |  BL = Borderline Lepromatous"],
        bg=C_LIGHT_TEAL, border=C_TEAL)

    E += mnemonic_box("LEPRA CELL vs EPITHELIOID CELL — 'Lepra = Lipid-laden, Lepromatous'",
        ["Lepra Cell = Lipid-laden macrophage = Lepromatous = Low immunity = Lots of bacilli",
         "Epithelioid Cell = Elongated macrophage = TB granuloma / Tuberculoid leprosy"],
        bg=C_LIGHT_YELLOW, border=C_YELLOW)

    E.append(key_fact("Leonine facies + saddle nose = Lepromatous leprosy. Anesthetic lesion with thickened peripheral nerve = Tuberculoid leprosy. Most disfiguring = Lepromatous."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 4 — VIRAL & FUNGAL INFECTIONS
# ────────────────────────────────────────────────────────────────────────────
def build_viral_fungal():
    E = []
    E += section_banner("COMMON VIRAL & FUNGAL INFECTIONS", 4, C_ORANGE)

    # VIRAL
    E += subsection("COMMON VIRAL INFECTIONS", C_ORANGE)

    viral_data = [
        ("INFLUENZA", "Type A, B, C\n(RNA virus, 8 segments)\nH and N surface proteins",
         "Antigenic drift (mutations) = epidemics\nAntigenic shift (recombination with animal virus) = PANDEMICS",
         "Diffuse alveolar damage (DAD)\nHyaline membranes\nInterstitial pneumonitis"),
        ("SARS-CoV-2\n(COVID-19)", "Enveloped +ve sense RNA\nSpike protein binds ACE2 on type II alveolar cells + nasopharynx",
         "Viral replication → immune overactivation\n'Cytokine storm'\nCoagulopathy, microthrombi",
         "DAD with hyaline membranes\nMicrothrombi in vessels\nMyocarditis, CNS infiltrates"),
        ("HERPES SIMPLEX\n(HSV-1/2)", "DNA virus (Herpesviridae)\nLatent in ganglia → reactivation",
         "Cell-to-cell spread\nImmune evasion via latency",
         "Cowdry type A intranuclear inclusions\nMultinucleated giant cells with 'ground-glass' nuclei"),
        ("CMV", "Large DNA virus\nDangerous in immunocompromised\n(AIDS, transplant patients)",
         "Reactivation when CMI falls",
         "OWL-EYE intranuclear inclusions (large, purple, surrounded by halo)\nSmaller cytoplasmic inclusions"),
        ("MEASLES\n(Rubeola)", "RNA Paramyxovirus\nDroplet transmission",
         "Enters via respiratory epithelium\nViraemia → dissemination",
         "Warthin-Finkeldey multinucleated giant cells (in lymphoid tissue)\nKoplik spots (buccal mucosa)\nSquamous metaplasia of bronchial epithelium"),
        ("EBV", "DNA Herpesvirus\nB-cell tropism",
         "EBV infects B cells via CD21\nPolyclonal B-cell proliferation",
         "Atypical lymphocytes (Downey cells)\nReactive germinal centres\nAssociated with Burkitt lymphoma, nasopharyngeal carcinoma"),
    ]
    E += comparison_table(
        ["Virus", "Features", "Pathogenesis", "Histology"],
        viral_data,
        col_widths=[2.5*cm, 4*cm, 4.5*cm, 3.5*cm],
        header_bg=C_ORANGE)

    E += subsection("VIRAL INCLUSION BODIES — EASY TABLE", C_RED)
    inclusion_data = [
        ("Cowdry type A (intranuclear)", "HSV, CMV, Yellow Fever", "Large eosinophilic, marginated chromatin"),
        ("Owl-eye inclusions (intranuclear)", "CMV", "Large purple nuclear inclusion + smaller cytoplasmic ones"),
        ("Negri bodies (cytoplasmic)", "Rabies", "Eosinophilic inclusions in neurons (hippocampus, cerebellum)"),
        ("Warthin-Finkeldey giant cells", "Measles", "Multinucleated giant cells in lymphoid tissue"),
        ("Henderson-Patterson bodies", "Molluscum contagiosum", "Large cytoplasmic inclusions"),
        ("Guarnieri bodies (cytoplasmic)", "Smallpox / Vaccinia", "Viral factories in cytoplasm"),
    ]
    E += comparison_table(["Inclusion Body", "Virus", "Description"],
                          inclusion_data,
                          col_widths=[4.5*cm, 3.5*cm, 6.5*cm],
                          header_bg=C_RED)

    # FUNGAL
    E += subsection("COMMON FUNGAL INFECTIONS", C_GREEN)
    fungal_data = [
        ("CANDIDA ALBICANS\n(Candidiasis)", "Pseudohyphae + budding yeast\nPAS / GMS stain",
         "Immunocompromise (neutropenia, AIDS)\nDiabetes, broad-spectrum antibiotics",
         "Superficial: Thrush, vaginitis\nDeep: esophageal, systemic\nNeutrophilic infiltrate with pseudohyphae invading tissue"),
        ("ASPERGILLUS\n(Aspergillosis)", "SEPTATE hyphae\n45° ACUTE ANGLE branching\nGMS / H&E stain",
         "Immunocompromised (neutropenic)\nPre-existing lung cavities\nAtopic patients (ABPA)",
         "3 forms: 1) Aspergilloma (fungal ball in cavity)\n2) ABPA (allergic, eosinophilic)\n3) Invasive: angioinvasion → infarction + hemorrhage"),
        ("CRYPTOCOCCUS\nNEOFORMANS", "Encapsulated yeast\nIndia ink: CLEAR HALO (capsule)\nMucicarmine stain: magenta capsule",
         "Inhalation from pigeon droppings\nOpportunistic in AIDS (CD4 < 200)",
         "Soap-bubble lesions in brain (gelatinous pseudocysts)\nMinimal inflammation in AIDS\nMeningoencephalitis\n'Gumball' appearance on Mucicarmine"),
        ("MUCOR / RHIZOPUS\n(Mucormycosis)", "BROAD non-septate hyphae\n90° RIGHT ANGLE branching\nGMS stain",
         "Diabetics (DKA) — rhinocerebral form\nNeutropenic patients — pulmonary form",
         "Angioinvasion → thrombosis → tissue INFARCTION\nRhinocerebral: orbit, palate, sinuses\nBlack necrotic eschars"),
        ("HISTOPLASMA\nCAPSULATUM", "Small intracellular yeast (2–4 μm)\nInside macrophages\nGMS / PAS stain",
         "Ohio/Mississippi river valleys\nInhalation of bird/bat droppings",
         "Mimics TB: granulomas, caseous necrosis, calcification\nTiny yeast inside macrophages\nDisseminated in AIDS (hepatosplenomegaly)"),
        ("PNEUMOCYSTIS\n(PCP)", "Cysts with 8 intracystic bodies\nGMS stain: dark cysts\nSilver stain",
         "Opportunistic: AIDS (CD4 < 200)\nImmunocompromised (transplant)",
         "Interstitial pneumonia\nFrothy, pink alveolar exudate ('cotton-candy' or 'honeycomb')\nNo granulomas"),
    ]
    E += comparison_table(
        ["Fungus", "Morphology/Stain", "Risk Factors", "Pathology"],
        fungal_data,
        col_widths=[2.8*cm, 3.5*cm, 3.5*cm, 4.7*cm],
        header_bg=C_GREEN)

    E += mnemonic_box("Fungal Hyphae — 'SANE vs BROAD'",
        ["SANE = Septate Acute aNgle = Aspergillus (45° branching)",
         "BROAD = Broad Right-angle Obtuse Angle Dimorphic = Mucor (90° branching, non-septate)"],
        bg=C_LIGHT_GREEN, border=C_GREEN)

    E += mnemonic_box("India Ink Stain — 'Crypto needs a CAP'",
        ["Cryptococcus = India Ink = Clear halo (Clear = Capsule = Crypto)"],
        bg=C_LIGHT_GREEN, border=C_GREEN)

    E.append(key_fact("Invasive Aspergillosis = angioinvasion (like Mucor). Mucor = Right angle, non-septate. Aspergillus = 45° acute angle, septate. CMV = Owl-eye. HSV = Cowdry A."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 5 — PRIMARY TUBERCULOSIS ★
# ────────────────────────────────────────────────────────────────────────────
def build_primary_tb():
    E = []
    E += section_banner("PRIMARY TUBERCULOSIS  ★", 5, C_DARK_BLUE)

    E.append(Paragraph(
        "<b>Definition:</b> Form of TB that develops in a <b>previously unexposed and unsensitized</b> individual. "
        "About <b>5%</b> of newly infected individuals develop significant disease. "
        "Caused by <i>Mycobacterium tuberculosis</i> — acid-fast bacillus (AFB), transmitted by <b>respiratory droplets</b>.", S_BODY))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("PATHOGENESIS", C_DARK_BLUE)
    patho = [
        " INHALATION of M. tuberculosis droplets",
        "       ↓",
        " PHASE 1 — INNATE RESPONSE (first ~3 weeks) — ASYMPTOMATIC",
        " Bacilli reach alveoli → phagocytosed by ALVEOLAR MACROPHAGES",
        " M. tb prevents phagolysosome fusion → survives inside macrophages",
        " Bacilli replicate → macrophages release chemokines → more monocytes recruited",
        " DENDRITIC CELLS carry mycobacterial antigens to HILAR LYMPH NODES",
        "       ↓",
        " PHASE 2 — ADAPTIVE IMMUNITY (~3 weeks) — Th1 RESPONSE",
        " DCs present antigens → Th1 cell differentiation (requires IL-12, IL-18)",
        " Th1 cells produce IFN-γ (CRITICAL mediator)",
        "       ↓",
        " IFN-γ activates macrophages → 3 mechanisms to kill bacteria:",
        "   1. Produces nitric oxide (NO) + reactive oxygen species (ROS)",
        "   2. Mobilizes defensins (cathelicidin)",
        "   3. Stimulates AUTOPHAGY (sequesters & destroys bacilli)",
        "       ↓",
        " Activated macrophages → EPITHELIOID HISTIOCYTES",
        "       ↓",
        " GRANULOMA FORMATION + CASEOUS NECROSIS",
        "       ↓",
        " 95%: Infection CONTAINED → Ghon complex heals → Ranke complex",
        " 5%: Progressive Primary TB (immunocompromised, HIV, malnutrition)",
    ]
    E.append(DiagramBox(patho, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("COMMON SITES OF PRIMARY TB", C_DARK_BLUE)
    sites_data = [
        ("1st", "LUNGS (>95%)", "Subpleural; lower part of UPPER LOBE or upper part of LOWER LOBE (close to pleura)"),
        ("2nd", "INTESTINE (ileum)", "From ingestion of M. bovis (infected milk) — rare now"),
        ("3rd", "TONSIL / PHARYNX", "Very rare; from oral entry"),
        ("4th", "SKIN", "Primary inoculation TB (rare)"),
    ]
    E += comparison_table(["Rank", "Site", "Notes"],
                          sites_data,
                          col_widths=[1.5*cm, 4*cm, 9*cm],
                          header_bg=C_DARK_BLUE)

    E += subsection("EVOLUTION OF THE TUBERCLE (GRANULOMA) — 5 STAGES", C_MED_BLUE)
    stages = [
        "STAGE 1 — INITIAL MACROPHAGE ACCUMULATION",
        "  Local accumulation of macrophages (HISTIOCYTES) at site of infection",
        "",
        "STAGE 2 — EPITHELIOID GRANULOMA",
        "  Macrophages transform into EPITHELIOID CELLS",
        "  (elongated, pink cytoplasm, 'footprint-shaped' nuclei — look like epithelium but ARE macrophages)",
        "  Surrounded by LYMPHOCYTES (mainly CD4+ Th1 cells)",
        "",
        "STAGE 3 — LANGHANS GIANT CELL FORMATION",
        "  Epithelioid cells fuse → LANGHANS GIANT CELLS",
        "  KEY FEATURE: Nuclei arranged in HORSESHOE / PERIPHERAL pattern",
        "",
        "STAGE 4 — CASEOUS NECROSIS",
        "  Centre becomes CASEOUS = cheese-like, amorphous, eosinophilic material",
        "  Due to DTH (delayed-type hypersensitivity) reaction",
        "  Caseous necrosis = PATHOGNOMONIC of TB",
        "",
        "STAGE 5 — RESOLUTION OR PROGRESSION",
        "  A) Fibrosis → Calcification (Ranke complex) — HEALING",
        "  B) Liquefaction → Cavity formation — SECONDARY TB",
    ]
    E.append(DiagramBox(stages, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))
    E.append(Spacer(1, 0.2*cm))

    # Tubercle diagram
    tubercle = [
        "        TB GRANULOMA (TUBERCLE) — DIAGRAM",
        "   ┌──────────────────────────────────────────────────┐",
        "   │  ┌────────────────────────────────────────────┐  │",
        "   │  │  ~~~ CASEOUS NECROSIS (CENTRE) ~~~         │  │",
        "   │  │  ~~~  (amorphous, cheese-like,   ~~~       │  │",
        "   │  │  ~~~   eosinophilic material)    ~~~       │  │",
        "   │  └────────────────────────────────────────────┘  │",
        "   │  [Epi][Epi]  LANGHANS GIANT CELL  [Epi][Epi]     │",
        "   │              O  O  O  O  O                        │",
        "   │           O (horseshoe nuclei) O                  │",
        "   │              O  O  O  O  O                        │",
        "   │  [Lym][Lym][Epi][Epi][Epi][Lym][Lym][Lym]       │",
        "   │       Lymphocytes surround epithelioid cells      │",
        "   │  === FIBROUS CAPSULE (outer layer) ===            │",
        "   └──────────────────────────────────────────────────┘",
        "   Epi = Epithelioid cell  |  Lym = Lymphocyte",
    ]
    E.append(DiagramBox(tubercle, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("PRIMARY COMPLEX — COMPONENTS  ★", C_RED)
    E.append(Paragraph(
        "The <b>Ghon's Complex (Primary Complex)</b> = THREE components:", S_BODY))

    complex_data = [
        ("1. GHON FOCUS\n(Parenchymal lesion)", "1–1.5 cm gray-white area of consolidation\nSubpleural; lower part of upper lobe / upper part of lower lobe\nCentre → caseous necrosis\nSEE: Parenchymal component"),
        ("2. LYMPHANGITIS\n(Connecting vessel)", "Inflammatory thickening of lymphatic channels\nBetween Ghon focus and hilar lymph nodes\nLinks parenchymal + nodal components"),
        ("3. HILAR LYMPHADENOPATHY\n(Nodal component)", "Caseous enlargement of regional (hilar/mediastinal) lymph nodes\nUsually MORE prominent than parenchymal lesion in children\nNodal caseous necrosis\nSEE: Nodal component"),
    ]
    E += comparison_table(["Component", "Features"],
                          complex_data,
                          col_widths=[4.5*cm, 10*cm],
                          header_bg=C_RED)

    complex_diag = [
        "    PRIMARY COMPLEX DIAGRAM",
        "    ┌────────────────────────────────────────────────┐",
        "    │                                                │",
        "    │  [LUNG PARENCHYMA]                             │",
        "    │                                                │",
        "    │    ●  GHON FOCUS (1-1.5 cm, subpleural)       │",
        "    │    |  (caseous centre, gray-white)             │",
        "    │    |                                           │",
        "    │    | ← LYMPHANGITIS (lymphatic channels)       │",
        "    │    |                                           │",
        "    │    ●  HILAR LYMPH NODES (caseous, enlarged)    │",
        "    │       (often larger than Ghon focus)           │",
        "    │                                                │",
        "    │    Together = GHON'S COMPLEX (Primary Complex) │",
        "    └────────────────────────────────────────────────┘",
    ]
    E.append(DiagramBox(complex_diag, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))

    E += mnemonic_box("Primary Complex = 'GHon FLH' (Focus + Lymphangitis + Hilum)",
        ["G = Ghon Focus (parenchymal lesion in lung)",
         "L = Lymphangitis (connecting lymphatics)",
         "H = Hilar lymphadenopathy (nodal lesion)",
         "All 3 together = Ghon Complex / Primary Complex"],
        bg=C_LIGHT_BLUE, border=C_DARK_BLUE)

    E.append(key_fact("Ghon Focus = parenchymal lesion only. Ghon Complex = Focus + Lymphangitis + Lymphadenitis. Ranke Complex = Calcified Ghon Complex (visible on X-ray)."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 6 — GHON'S COMPLEX ★★★
# ────────────────────────────────────────────────────────────────────────────
def build_ghon_complex():
    E = []
    E += section_banner("GHON'S COMPLEX — Gross, Microscopic & Fate  ★★★", 6, C_GREEN)

    E.append(Paragraph(
        "<b>Ghon's Complex</b> = Ghon Focus (parenchymal lung lesion) + Lymphangitis + "
        "Caseous hilar lymphadenopathy in PRIMARY TUBERCULOSIS. "
        "Named after Anton Ghon (1912).", S_BODY))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("GROSS FEATURES", C_GREEN)
    E.append(Paragraph("<b>A. Ghon Focus (Parenchymal Lesion):</b>", S_SUBSECTION))
    gross_focus = [
        "Location: Subpleural; lower part of UPPER LOBE or upper part of LOWER LOBE",
        "Size: 1–1.5 cm",
        "Colour: Gray-white area of consolidation",
        "Centre: Caseous necrosis — yellow-white, cheese-like, friable material",
        "Surrounding: Zone of grey consolidation (solid pneumonia)",
        "Pleural surface: May show fibrinous exudate / pleural adhesions",
    ]
    for g in gross_focus:
        E.append(bp(g))

    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>B. Hilar Lymph Nodes:</b>", S_SUBSECTION))
    gross_nodes = [
        "Enlarged, discrete or matted together at hilum",
        "Cut section: Yellow-white caseous material (more extensive than Ghon focus)",
        "In children: nodal lesion often LARGER than parenchymal lesion",
        "Periadenitis: nodes matted to adjacent structures",
    ]
    for g in gross_nodes:
        E.append(bp(g))

    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>C. Lymphatics (Lymphangitis):</b>", S_SUBSECTION))
    E.append(bp("Thickened, visible lymphatic channels between Ghon focus and hilar nodes"))
    E.append(bp("May show 'beaded' appearance due to granulomas along the lymphatic channel"))

    E += subsection("MICROSCOPIC FEATURES", C_GREEN)
    micro_table = [
        ("AT GHON FOCUS", "1. CASEOUS NECROSIS at centre:\n   • Amorphous, granular, eosinophilic material\n   • Ghost cell outlines ('tombstone cells')\n   • Loss of all cellular architecture\n   • No living cells within necrotic core\n\n2. GRANULOMATOUS INFLAMMATION surrounding necrosis:\n   • EPITHELIOID CELLS (activated macrophages)\n     - Elongated, pale pink cytoplasm\n     - 'Footprint-shaped' / oblong nuclei\n   • LANGHANS GIANT CELLS\n     - Peripheral / horseshoe nucleus arrangement\n   • LYMPHOCYTES (mainly CD4+ T cells)\n   • Occasional plasma cells and fibroblasts\n\n3. FIBROUS CAPSULE (outer rim):\n   • Fibroblasts + collagen encapsulating granuloma\n\n4. AFB STAIN (Ziehl-Neelsen):\n   • Red acid-fast bacilli (scanty in primary TB)\n   • More abundant in immunocompromised"),
        ("AT HILAR LYMPH NODES", "• Similar caseating granulomas\n• Effacement of normal nodal architecture\n• Caseous necrosis (may be more extensive)\n• Epithelioid cells + Langhans giant cells\n• Peripheral lymphocyte rim\n• Periadenitis: inflammatory capsular thickening"),
        ("IN IMMUNOCOMPROMISED\n(HIV, CD4 < 200)", "• Granulomas ABSENT\n• Sheets of foamy macrophages with NUMEROUS bacilli\n• No caseous necrosis\n• AFB stain: heavily loaded with acid-fast bacilli\n• = Progressive Primary TB pattern"),
    ]
    E += comparison_table(["Site", "Microscopic Features"],
                          micro_table,
                          col_widths=[3.5*cm, 11*cm],
                          header_bg=C_GREEN)

    # Microscopy diagram
    micro_diag = [
        "    MICROSCOPY OF GHON FOCUS — DIAGRAM",
        "    ┌────────────────────────────────────────────────────┐",
        "    │                                                    │",
        "    │  [FIBROUS CAPSULE] ─────────────────────────────── │",
        "    │                                                    │",
        "    │  Lymphocytes  [L][L][L][L][L][L][L][L]            │",
        "    │                                                    │",
        "    │  Epithelioid cells: [Epi][Epi][Epi][Epi][Epi]     │",
        "    │                                                    │",
        "    │  Langhans Giant Cell:  O O O O O O                 │",
        "    │                       O  LARGE   O  (horseshoe    │",
        "    │                       O  CELL    O   nuclei at    │",
        "    │                       O O O O O O    periphery)   │",
        "    │                                                    │",
        "    │  CASEOUS NECROSIS: ~~~ amorphous ~~~ (centre)      │",
        "    │  ~~~ eosinophilic granular debris ~~~ no cells ~~~ │",
        "    │                                                    │",
        "    └────────────────────────────────────────────────────┘",
    ]
    E.append(DiagramBox(micro_diag, bg=C_LIGHT_GREEN, border=C_GREEN))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("FATE OF GHON'S COMPLEX  ★★★", C_RED)
    fate_diag = [
        "                    GHON'S COMPLEX",
        "                          |",
        "            ┌─────────────┴─────────────┐",
        "         95%                           5%",
        "    Normal immunity               Immunocompromised",
        "         |                             |",
        "         ↓                             ↓",
        "     HEALING                 PROGRESSIVE PRIMARY TB",
        "         |                             |",
        "    ┌────┴────┐               Caseous pneumonia",
        "    ↓         ↓               Miliary spread",
        " FIBROSIS  CALCIFICATION      Tuberculous meningitis",
        "            ↓",
        "       RANKE COMPLEX",
        "   (visible on chest X-ray",
        "    as calcified nodule)",
        "         |",
        "         ↓ (if immunity wanes years later)",
        "    REACTIVATION → SECONDARY TB",
        "    (apical lung cavity)",
    ]
    E.append(DiagramBox(fate_diag, bg=C_LIGHT_GREEN, border=C_GREEN))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("FATE — DETAILED TABLE", C_GREEN)
    fate_data = [
        ("RESOLUTION (95%)", "Immune containment via Th1/IFN-γ", "Fibrosis → Calcification", "Ranke complex on X-ray"),
        ("PROGRESSIVE PRIMARY TB (5%)", "Immunocompromised, HIV, severe malnutrition", "Caseous pneumonia, lobar consolidation", "No granulomas in HIV"),
        ("MILIARY TB", "Haematogenous dissemination via erosion into blood vessel", "Millet-seed foci (1–2 mm) throughout ALL organs (lung, liver, spleen, kidney, brain)", "Classic 'snowstorm' on CXR"),
        ("TB MENINGITIS", "Haematogenous/lymphatic spread to meninges", "Subependymal granuloma ruptures into CSF spaces", "Basal exudate, vasculitis"),
        ("PLEURAL EFFUSION", "Delayed hypersensitivity reaction to TB antigens in pleural space", "Serous lymphocytic effusion", "Exudate, lymphocyte-rich"),
        ("REACTIVATION (Secondary TB)", "Waning immunity (years/decades later)", "Apical lung cavity; cavitation, fibrosis, spread", "AFB-positive sputum"),
    ]
    E += comparison_table(["Fate", "Mechanism", "Pathology", "Notes"],
                          fate_data,
                          col_widths=[3.5*cm, 4.5*cm, 4.5*cm, 2*cm],
                          header_bg=C_GREEN)

    E += subsection("KEY TERMINOLOGY COMPARISON", C_DARK_BLUE)
    terminology = [
        ("Ghon Focus", "Parenchymal lung lesion only (1–1.5 cm caseous nodule)"),
        ("Ghon Complex", "Ghon Focus + Lymphangitis + Hilar lymphadenopathy"),
        ("Ranke Complex", "CALCIFIED Ghon Complex (healed primary TB) — visible on X-ray"),
        ("Primary Complex", "Same as Ghon Complex (broader term)"),
        ("Miliary TB", "Haematogenous dissemination → millet-seed foci throughout body"),
        ("Secondary TB", "Reactivation TB in previously sensitized host — APICAL cavitation"),
    ]
    E += comparison_table(["Term", "Definition"],
                          terminology,
                          col_widths=[3.5*cm, 11*cm],
                          header_bg=C_DARK_BLUE)

    E += mnemonic_box("Fate of Ghon Complex — 'FRAME'",
        ["F = Fibrosis (heals with fibrosis)",
         "R = Ranke complex (calcified form, visible on X-ray)",
         "A = Activation (reactivation → secondary TB if immunity wanes)",
         "M = Miliary spread (haematogenous)",
         "E = Erosion into bronchus (spread to other lung areas) / Effusion"],
        bg=C_LIGHT_GREEN, border=C_GREEN)

    E += mnemonic_box("Granuloma vs Abscess — 'Granuloma = Contained; Abscess = Liquefied'",
        ["Granuloma (TB) = CASEOUS necrosis = dry, cheese-like, NO pus",
         "Abscess (Pyogenic) = LIQUEFACTIVE necrosis = pus, neutrophils",
         "Caseous necrosis = ONLY seen in TB (pathognomonic)"],
        bg=C_LIGHT_YELLOW, border=C_YELLOW)

    E.append(key_fact("MUHS favourite: List 5 fates of Ghon complex. Always include Ranke complex definition. Miliary TB = haematogenous spread with millet-seed lesions everywhere."))

    E.append(Spacer(1, 0.5*cm))
    E.append(divider(C_GREEN))
    E.append(Spacer(1, 0.3*cm))
    E.append(Paragraph("END OF REVISION NOTES", make_style('End',
        fontSize=12, textColor=C_MID_GREY, fontName='Helvetica-Bold',
        alignment=TA_CENTER)))
    E.append(Paragraph("Robbins, Cotran & Kumar — Pathologic Basis of Disease, 10e | Robbins & Kumar Basic Pathology",
        make_style('EndSub', fontSize=8.5, textColor=C_MID_GREY,
                   fontName='Helvetica-Oblique', alignment=TA_CENTER)))
    return E


# ── ASSEMBLE & BUILD ──────────────────────────────────────────────────────────
def build_pdf():
    os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True)
    doc = SimpleDocTemplate(
        OUTPUT_PATH,
        pagesize=A4,
        leftMargin=2*cm,
        rightMargin=2*cm,
        topMargin=2.2*cm,
        bottomMargin=1.8*cm,
        title="MUHS 2nd MBBS Pathology Rapid Revision",
        author="Robbins & Kumar"
    )

    all_elements = []
    all_elements += build_cover()
    all_elements += build_malaria()
    all_elements += build_cysticercosis()
    all_elements += build_leprosy()
    all_elements += build_viral_fungal()
    all_elements += build_primary_tb()
    all_elements += build_ghon_complex()

    doc.build(
        all_elements,
        onFirstPage=on_first_page,
        onLaterPages=on_later_pages
    )
    print(f"PDF successfully generated: {OUTPUT_PATH}")


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

ls /home/daytona/workspace/muhs-study-guide/

Editing File

~/muhs-study-guide/generate_pdf.py

Error: String not found in file: '#!/usr/bin/env python3
"""
MUHS 2nd MBBS Pathology - Comprehensive Revision PDF
Topics: Malaria, Cysticercosis, Leprosy, Viral/Fungal Infections,
        Primary TB, Ghon's Complex
Based on Robbins & Kumar Pathology
"""'
Running Command

cat /home/daytona/workspace/muhs-study-guide/generate_pdf.py | head -5

This is a shared conversation. Sign in to Orris to start your own chat.