Here is the highly dense, exam-focused breakdown of Cranial Nerves I through VIII tailored specifically for the FMGE, NEXT, and USMLE. These are organized exactly like your prompt, focusing on The Exact Symptoms paired with the precise High-Yield Board Keywords examiners use to trigger the diagnosis. ------------------------------ ## 👃 CN I: Olfactory Nerve## The Exact Symptoms (What the Patient Experiences) * Loss of Smell: Total inability to detect odors (anosmia). * Taste Alteration: Complaints that food tastes completely bland or like cardboard (because flavor appreciation requires olfaction). ## High-Yield Exam Keywords & Clues * Trauma: "Fracture of the cribriform plate" or "ethmoid bone" following a motor vehicle accident. * Fluid Leak: "CSF rhinorrhea" (clear nasal discharge that tests positive for beta-2 transferrin). * Tumor: "Foster Kennedy Syndrome" (ipsilateral anosmia, ipsilateral optic atrophy, contralateral papilledema due to a frontal lobe meningioma). ------------------------------ ## 👁️ CN II: Optic Nerve## The Exact Symptoms (What the Patient Experiences) * Vision Loss: Blindness in one eye, or missing parts of the visual field (e.g., losing peripheral vision and bumping into door frames). * Pain with Eye Movement: Deep ache behind the eye when looking around. ## High-Yield Exam Keywords & Clues * Pupil Reflex: Marcus Gunn Pupil or Relative Afferent Pupillary Defect (RAPD) (when light shines in the affected eye, both pupils appear to dilate instead of constrict). * Visual Field Defects: * Bitemporal hemianopsia $\rightarrow$ Pituitary adenoma compressing the optic chiasm. * Ipsilateral anopsia $\rightarrow$ Monocular blindness from an optic nerve lesion. * Pathology: Optic neuritis linked to Multiple Sclerosis (MS). ------------------------------ ## 👁️‍🗨️ CN III: Oculomotor Nerve## The Exact Symptoms (What the Patient Experiences) * Severe Diplopia: Constant double vision when trying to look in any direction. * Drooping Eyelid: The eyelid shuts completely on one side and cannot be lifted voluntarily. ## High-Yield Exam Keywords & Clues * Eye Position: "Down and Out" eye (due to the unopposed action of CN IV and CN VI). * Eyelid: Severe ptosis (paralysis of levator palpebrae superioris). * Pupil Size: Mydriasis (fixed, dilated pupil due to loss of parasympathetic constrictor fibers). * Medical vs. Surgical Rule (Crucial for FMGE): * Pupil-sparing $\rightarrow$ Diabetic/Ischemic neuropathy (motor fibers inside are damaged, parasympathetic fibers on the outside are saved). * Pupil-dilated $\rightarrow$ Posterior Communicating Artery (PCom) aneurysm compressing the nerve from the outside. ------------------------------ ## 📉 CN IV: Trochlear Nerve## The Exact Symptoms (What the Patient Experiences) * Vertical Double Vision: The patient sees two vertical images layered on top of each other. * Difficulty Walking Downstairs: Severe trouble looking downward and inward; patients frequently trip on stairs or struggle to read books. ## High-Yield Exam Keywords & Clues * Head Posture: "Patient tilts head to the opposite side" to correct the double vision. * Muscle: Paralysis of the Superior Oblique muscle. * Trauma: Longest intracranial course; highly susceptible to shear injury from minor head trauma. ------------------------------ ## ⚡ CN V: Trigeminal Nerve## The Exact Symptoms (What the Patient Experiences) * Lancinating Pain: Sudden, excruciating, electric shock-like or stabbing facial pain. Triggered by light touch, washing the face, shaving, or a gust of wind. * Chewing Weakness: Difficulty biting down or chewing hard foods. ## High-Yield Exam Keywords & Clues * Neuralgia: Trigeminal Neuralgia (Tic Douloureux). * Reflex: Absent Corneal Reflex (CN V1 provides the afferent/sensory limb; CN VII provides the efferent/motor limb). * Jaw Deviation: "Jaw deviates TOWARD the side of the lesion" when opened (due to weakness of the ipsilateral lateral pterygoid muscle). * Sensation: Sensory loss to the anterior 2/3 of the tongue (General sensation via Lingual nerve, a branch of CN V3). ------------------------------ ## ↔️ CN VI: Abducens Nerve## The Exact Symptoms (What the Patient Experiences) * Horizontal Double Vision: Images overlap horizontally when the patient tries to look toward the lateral side of the affected eye. ## High-Yield Exam Keywords & Clues * Eye Position: Esotropia (medial strabismus / the eye turns inward toward the nose at rest). * Muscle: Paralysis of the Lateral Rectus muscle. * Intracranial Pressure: "False Localizing Sign" (highly sensitive to increased ICP because it stretches over the clivus bone; an injury does not necessarily mean a brainstem lesion). ------------------------------ ## 🎭 CN VII: Facial Nerve## The Exact Symptoms (What the Patient Experiences) * Facial Asymmetry: Complete flatting of the forehead wrinkles, inability to close the eye, and sagging corner of the mouth on one side. * Sound Sensitivity: Normal sounds (like a running faucet or TV) sound painfully loud. * Taste Loss & Dryness: Food tastes weird on the front of the tongue; dry mouth and dry eye. ## High-Yield Exam Keywords & Clues * UMN vs. LMN Rule (Guaranteed Exam Question): * Bell's Palsy (LMN): Complete ipsilateral facial paralysis INVOLVING the forehead (cannot wrinkle forehead or close eye). * Stroke (UMN): Forehead sparing (can still wrinkle both sides of the forehead due to bilateral cortical innervation). * Keywords: Hyperacusis (paralysis of stapedius muscle) • Loss of taste on the anterior 2/3 of the tongue (Chorda tympani) • Corneal ulceration due to inability to close eyelid (Orbicularis oculi failure). ------------------------------ ## 👂 CN VIII: Vestibulocochlear Nerve## The Exact Symptoms (What the Patient Experiences) * Hearing Loss: Difficulty hearing speech, especially in crowds. * Vertigo: Sensation that the room is spinning wildly, accompanied by nausea, vomiting, and loss of balance. * Ringing: A constant, high-pitched buzzing or roaring in the ear (tinnitus). ## High-Yield Exam Keywords & Clues * Tuning Fork Tests: * Rinne test: Positive (Normal: Air Conduction > Bone Conduction, but overall volume is reduced). * Weber test: Lateralizes to the healthy/normal ear (indicates Sensorineural hearing loss). * Tumor: Acoustic Neuroma (Vestibular Schwannoma) located in the Cerebellopontine Angle (CP angle). * Syndrome Connection: Bilateral acoustic neuromas $\rightarrow$ Neurofibromatosis Type 2 (NF-2). ------------------------------ If you are practicing for the upcoming exam, would you like to review brainstem cross-sections (Midbrain, Pons, Medulla) to see where these nerve nuclei live, or would you prefer a set of integrated clinical vignettes to practice identifying these keywords?

Asking for Preferences
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
I have enough high-yield library data. Here is the full CN IX-XII breakdown in your exact format:

🗣️ CN IX: Glossopharyngeal Nerve

The Exact Symptoms (What the Patient Experiences)

  • Throat Pain on Swallowing: Sudden, agonizing, electric shock-like pain deep in the throat, tonsil, or ear triggered by swallowing, coughing, or talking.
  • Loss of Gag Reflex: The back of the throat is stimulated but the patient does not gag - food pools in the pharynx and the patient chokes.
  • Taste Loss on the Posterior Tongue: Food, especially bitter and sour, loses all flavor on the back one-third of the tongue.
  • Syncope: Brief fainting spells associated with swallowing (cardiac slowing via the vagal arc).

High-Yield Exam Keywords & Clues

  • Neuralgia: Glossopharyngeal Neuralgia - lancinating throat/ear pain triggered by swallowing. Distinguished from Trigeminal Neuralgia by its location (throat, not face). Can trigger a vasovagal response and cause cardiac syncope.
  • Reflex Arcs (Two Guaranteed Questions):
    • Gag reflex afferent limb = CN IX (sensory, posterior pharynx) | efferent limb = CN X (motor, pharynx).
    • Carotid sinus reflex afferent limb = CN IX (pressure receptor in carotid body) | efferent limb = CN X (slows heart).
  • Sensation: Posterior 1/3 of the tongue - taste AND general sensation both carried by CN IX (contrast with anterior 2/3 where taste = Chorda Tympani/CN VII and general sensation = Lingual nerve/CN V3).
  • Stylopharyngeus Muscle: The only muscle innervated solely by CN IX - elevates the larynx and pharynx during swallowing.
  • Tumor: Glomus jugulare (paraganglioma) at the jugular foramen crushes CN IX, X, and XI together.

🫁 CN X: Vagus Nerve

The Exact Symptoms (What the Patient Experiences)

  • Hoarse Voice: Rough, breathy, or completely absent voice (dysphonia/aphonia) due to vocal cord paralysis.
  • Dysphagia: Difficulty swallowing liquids more than solids; liquid comes back out through the nose (nasal regurgitation) due to soft palate failure.
  • Uvular Deviation: On exam, the uvula and soft palate swing away from the paralyzed side toward the healthy side when the patient says "Ahh."
  • Autonomic Dysfunction: Resting tachycardia, abnormal heart rate, or gut motility disturbances (nausea, early satiety, gastroparesis).

High-Yield Exam Keywords & Clues

  • Uvula Rule (Guaranteed Exam Question):
    • CN X lesion → uvula deviates AWAY from the side of the lesion (healthy side muscles pull it over).
    • Compare to CN XII: tongue deviates TOWARD the side of the lesion.
  • Recurrent Laryngeal Nerve (RLN) - Highest Yield Branch:
    • Left RLN wraps under the aortic arch → damaged by aortic aneurysm, lung cancer (left hilar mass), mediastinal lymphadenopathy, or thoracic surgery.
    • Right RLN wraps under the subclavian artery → damaged by right-sided Pancoast tumor or thyroid surgery.
    • Bilateral RLN palsy → stridor, respiratory distress (emergency).
  • Syndrome: Wallenberg Syndrome (Lateral Medullary Syndrome from PICA occlusion) - includes CN IX and X involvement: ipsilateral palatal palsy, hoarseness, dysphagia + ipsilateral Horner's + contralateral loss of pain and temperature.
  • Palate Innervation: Vagus innervates ALL soft palate muscles EXCEPT tensor veli palatini (CN V3, mandibular branch).

💪 CN XI: Spinal Accessory Nerve

The Exact Symptoms (What the Patient Experiences)

  • Shoulder Drop: The shoulder droops on the affected side and the patient cannot shrug it upward against resistance (trapezius weakness).
  • Neck Weakness: Inability to turn the head toward the opposite side against resistance (sternocleidomastoid weakness).
  • Winging of the Scapula: The medial border of the scapula flares outward at rest and worsens when the arm is raised - the trapezius can no longer hold the scapula flat against the chest wall.

High-Yield Exam Keywords & Clues

  • Muscles (Both Must Be Memorized):
    • Sternocleidomastoid (SCM): Turns head to the OPPOSITE side. Test by asking the patient to turn their chin toward the shoulder while you resist.
    • Trapezius: Shrugs shoulder upward. Test by asking the patient to shrug against resistance.
  • UMN vs. LMN Rule (Tricky Question):
    • SCM receives contralateral cortical control (a right hemispheric stroke paradoxically weakens the left SCM).
    • Trapezius receives ipsilateral cortical control.
  • Clinical Setting: CN XI is the most commonly injured cranial nerve during neck dissection surgery (radical or modified). Always appear in vignettes about post-surgical shoulder pain and scapular winging.
  • Jugular Foramen Syndromes (Multi-Nerve Clusters):
    • Vernet Syndrome = CN IX + X + XI (jugular foramen lesion - basal skull fracture, glomus jugulare tumor).
    • Collet-Sicard Syndrome = CN IX + X + XI + XII (lesion extends to include the hypoglossal canal).

👅 CN XII: Hypoglossal Nerve

The Exact Symptoms (What the Patient Experiences)

  • Tongue Deviation: When the patient sticks out their tongue, it deflects to one side.
  • Dysarthria: Speech sounds thick, slurred, or like the patient has a heavy object in their mouth ("hot potato voice" for lingual sounds - "la, la, la" is especially affected).
  • Dysphagia: Difficulty chewing and moving food into position to swallow.
  • Tongue Atrophy & Fasciculations: On LMN lesion, the affected half of the tongue wastes away and visibly twitches at rest.

High-Yield Exam Keywords & Clues

  • Tongue Deviation Rule (Guaranteed Exam Question):
    • LMN lesion (nerve itself) → tongue deviates TOWARD the side of the lesion (the weak side is pushed over by the healthy genioglossus on the opposite side).
    • UMN lesion (stroke, cortical) → tongue deviates AWAY from the side of the lesion (same direction as hemiplegia; the healthy cortex controls ipsilateral tongue movement less).
  • Fasciculations = LMN Sign: Tongue fasciculations are a classic feature of ALS (Amyotrophic Lateral Sclerosis) and direct nerve injury. UMN lesions produce a spastic, slow tongue without fasciculations.
  • Anatomy Pitfall: CN XII exits through the hypoglossal canal of the occipital bone - NOT the jugular foramen. This is why CN XII is often spared in pure jugular foramen syndromes (Vernet) but included in Collet-Sicard.
  • Clinical Setting: CN XII palsy appears in vignettes about carotid endarterectomy complications, penetrating neck trauma, nasopharyngeal carcinoma, and skull base metastases.

🏥 Bonus: Multi-Nerve Syndrome Summary Table (Exam Trap Card)

SyndromeNerves InvolvedClassic Cause
VernetIX, X, XIJugular foramen tumor/fracture
Collet-SicardIX, X, XI, XIIJugular foramen + hypoglossal canal
VillaretIX, X, XI, XII + Horner'sRetroparotid space (parotid tumor, carotid dissection)
SchmidtX, XINucleus ambiguus + CN XI
JacksonX, XI, XIIMedullary lesion (nucleus ambiguus region)

🔑 Ultimate Memory Rule for CN IX-XII

Nerve"The One Thing" Examiners Test
CN IXGag reflex afferent + posterior 1/3 tongue (taste AND general sensation) + glossopharyngeal neuralgia with syncope
CN XUvula deviates AWAY + left RLN = aortic aneurysm/lung cancer + Wallenberg
CN XIPost-neck dissection shoulder drop + SCM turns head OPPOSITE + Vernet syndrome
CN XIITongue deviates TOWARD (LMN) + fasciculations = ALS + exits hypoglossal canal (not jugular foramen)

Want to continue with the brainstem cross-sections (Midbrain/Pons/Medulla nuclei mapped to these nerves), or move straight into integrated clinical vignettes combining CN I-XII for full exam practice?

1 Create a comprehensive PDF with CN I-XII anatomy diagrams and clinical correlations 2 Generate PPTX slides: Brainstem cross-sections (Midbrain/Pons/Medulla) with nerve nuclei labeled 3 Build integrated clinical vignettes (10-15) combining CN I-XII for FMGE/USMLE practice 4 Make a comparison table: CN syndromes (Vernet, Collet-Sicard, Wallenberg, etc.)

Reading File
Reading File
Reading File
general-purpose

Create a comprehensive, exam-focused PDF document on Cranial Nerves I-XII for FMGE/NEXT/USMLE students. Save it to /home/daytona/workspace/cranial-nerves/CN_Complete_Guide.pdf Use the PDF skill at /home/daytona/skills/pdf/SKILL.md — read it first. Use ReportLab to generate the PDF. ## Content Requirements The PDF should have the following sections: ### COVER PAGE Title: "Cranial Nerves I–XII: Complete Board Review" Subtitle: "FMGE | NEXT | USMLE High-Yield Guide" A clean medical blue/white professional design. ### SECTION 1: CN I–IV (Pages 2–5) For each nerve (CN I, II, III, IV) create a dedicated page with: - Nerve name, number, and emoji icon in header - A clear ASCII/text diagram showing the nerve pathway (origin nucleus → exit point → target) - Fiber types (sensory/motor/parasympathetic) - Clinical correlations table with 2 columns: Lesion/Disease | Key Finding - High-yield board keywords box (shaded) ### SECTION 2: CN V–VIII (Pages 6–9) Same format as above for CN V, VI, VII, VIII. ### SECTION 3: CN IX–XII (Pages 10–13) Same format as above for CN IX, X, XI, XII. ### SECTION 4: Clinical Correlations & Syndromes (Pages 14–15) A full comparison table of major CN syndromes: | Syndrome | Nerves | Location | Classic Cause | Key Findings | | Vernet | IX, X, XI | Jugular foramen | Glomus jugulare / basal skull fracture | Dysphagia, hoarse, shoulder drop | | Collet-Sicard | IX, X, XI, XII | Jugular foramen + hypoglossal canal | Skull base tumor | Above + tongue deviation | | Villaret | IX, X, XI, XII + Horner's | Retroparotid space | Parotid tumor, carotid dissection | Above + Horner's syndrome | | Wallenberg | CN IX, X nuclei + tracts | Lateral medulla (PICA) | PICA occlusion | Dysphagia, hoarse, ipsilateral Horner's, contralateral pain/temp loss | | Foster Kennedy | CN I, II | Frontal lobe | Frontal meningioma | Ipsilateral anosmia + optic atrophy, contralateral papilledema | | Weber | CN III + corticospinal | Midbrain (cerebral peduncle) | PCA occlusion | Ipsilateral CN III palsy + contralateral hemiplegia | | Benedikt | CN III + red nucleus | Midbrain tegmentum | PCA branch occlusion | Ipsilateral CN III palsy + contralateral tremor/ataxia | | Millard-Gubler | CN VI, VII + corticospinal | Pons | Pontine infarct | Ipsilateral CN VI + VII palsy, contralateral hemiplegia | ### SECTION 5: Quick-Reference Summary Table (Page 16) A full table of all 12 cranial nerves: Columns: CN # | Name | Fiber Type | Exit Foramen | Key Function | Board Keyword Use this data: - CN I | Olfactory | Sensory | Cribriform plate | Smell | Anosmia, Foster Kennedy - CN II | Optic | Sensory | Optic canal | Vision | RAPD, bitemporal hemianopsia - CN III | Oculomotor | Motor + Parasympathetic | Superior orbital fissure | Eye movement (SR, IR, MR, IO), pupil constriction, eyelid | Down-and-out, ptosis, mydriasis, PComm aneurysm - CN IV | Trochlear | Motor | Superior orbital fissure | Superior oblique (down+in gaze) | Head tilt, longest intracranial course, stair difficulty - CN V | Trigeminal | Sensory + Motor | V1: SOF, V2: foramen rotundum, V3: foramen ovale | Face sensation, chewing | Tic douloureux, jaw deviation toward lesion, corneal reflex afferent - CN VI | Abducens | Motor | Superior orbital fissure | Lateral rectus (abduction) | Esotropia, false localizing sign, increased ICP - CN VII | Facial | Motor + Sensory + Parasympathetic | Stylomastoid foramen | Facial expression, taste (ant 2/3 tongue), lacrimation, salivation | Bell's palsy, UMN forehead sparing, hyperacusis, chorda tympani - CN VIII | Vestibulocochlear | Sensory | Internal acoustic meatus | Hearing + balance | Weber lateralizes to good ear (SNHL), acoustic neuroma, NF-2 - CN IX | Glossopharyngeal | Mixed | Jugular foramen | Taste + sensation post 1/3 tongue, gag afferent, stylopharyngeus | Gag reflex afferent, carotid sinus reflex, glossopharyngeal neuralgia with syncope - CN X | Vagus | Mixed | Jugular foramen | Palate, pharynx, larynx, autonomics | Uvula away from lesion, left RLN = aortic aneurysm/lung CA, Wallenberg - CN XI | Spinal Accessory | Motor | Jugular foramen | SCM, trapezius | Neck dissection injury, shoulder drop, Vernet syndrome - CN XII | Hypoglossal | Motor | Hypoglossal canal | Tongue movement | Tongue toward lesion (LMN), fasciculations = ALS, Collet-Sicard ## Design Notes - Use ReportLab with professional formatting - Blue (#1a3a6b) headers, white backgrounds - Gray shaded boxes for high-yield keywords - Tables with alternating row colors - Clear fonts: Helvetica for body, bold for headers - Page numbers in footer - Create the workspace directory if it doesn't exist: /home/daytona/workspace/cranial-nerves/ Return the exact file path of the created PDF.

general-purpose

Create a professional PowerPoint presentation on Brainstem Cross-Sections with Cranial Nerve Nuclei for FMGE/NEXT/USMLE students. Save it to /home/daytona/workspace/cranial-nerves/Brainstem_CrossSections.pptx Read the PPTX skill at /home/daytona/skills/pptx/SKILL.md first, then read /home/daytona/skills/pptx/pptxgenjs.md. Use pptxgenjs (Node.js) to create the file. Create the workspace directory first: mkdir -p /home/daytona/workspace/cranial-nerves/ ## Design Theme - Dark navy background (#0d1b2a) for title + section slides - Light gray/white (#f0f4f8) for content slides - Accent color: medical gold (#c8a84b) for highlights and borders - Deep blue (#1a3a6b) for subtitles and headers - Clean, modern medical aesthetic ## Slide Structure (20+ slides) ### Slide 1 - Title Slide (dark bg) Title: "Brainstem Cross-Sections & Cranial Nerve Nuclei" Subtitle: "FMGE | NEXT | USMLE Board Review" Footer: "Midbrain • Pons • Medulla" ### Slide 2 - Overview (dark bg) Title: "The Brainstem at a Glance" Content - 3 column layout showing: - MIDBRAIN: CN III, IV - PONS: CN V, VI, VII, VIII - MEDULLA: CN IX, X, XI, XII Tagline at bottom: "12 cranial nerves, 3 levels — know which lives where" ### Slide 3 - Brainstem Levels Diagram (light bg) Title: "Brainstem Structural Overview" Use shapes (rectangles stacked) to draw a schematic brainstem: - Top rectangle (gold): MIDBRAIN - CN III, IV - Middle rectangle (blue): PONS - CN V, VI, VII, VIII - Bottom rectangle (teal): MEDULLA - CN IX, X, XI, XII Labels and connecting lines ### Slide 4 - Section Header: MIDBRAIN (dark bg) Large text: "MIDBRAIN" Subtitle: "CN III & CN IV Nuclei" Level label: "Superior & Inferior Colliculus Level" ### Slide 5 - Midbrain Cross-Section: Superior Colliculus Level (light bg) Title: "Midbrain: Level of Superior Colliculus (CN III)" Use drawn shapes to represent cross-section: - Central canal (cerebral aqueduct) — small blue oval center - Periaqueductal gray (PAG) — ring around aqueduct - Edinger-Westphal nucleus (parasympathetic) — labeled dot upper - CN III nucleus — labeled dot - Red nucleus — labeled circle (red fill) - Cerebral peduncle — large rounded rectangle bottom - Substantia nigra — dark bar above peduncle Key labels with leader lines (text boxes with arrows) Below diagram: "CN III exits ANTERIORLY between PCA and SCA — PCom aneurysm compresses it here" ### Slide 6 - Midbrain Cross-Section: Inferior Colliculus Level (light bg) Title: "Midbrain: Level of Inferior Colliculus (CN IV)" Similar cross-section: - CN IV nucleus (only CN to exit POSTERIORLY) - Decussates before exiting - MLF (medial longitudinal fasciculus) Key fact box: "CN IV — ONLY cranial nerve to exit from the DORSAL surface of the brainstem" ### Slide 7 - Midbrain Clinical Correlations (light bg) Title: "Midbrain Syndromes — High Yield" 3-column table: | Syndrome | Structures | Findings | | Weber | CN III + cerebral peduncle | Ipsilateral CN III palsy + contralateral hemiplegia | | Benedikt | CN III + red nucleus | Ipsilateral CN III palsy + contralateral tremor | | Claude | CN III + superior cerebellar peduncle | CN III palsy + contralateral ataxia | | Nothnagel | CN III + superior cerebellar peduncle (bilateral) | Bilateral CN III palsies + cerebellar ataxia | Bold red keyword boxes for Weber and Benedikt (most tested) ### Slide 8 - Section Header: PONS (dark bg) Large text: "PONS" Subtitle: "CN V, VI, VII, VIII Nuclei" Level label: "Upper, Middle & Lower Pons" ### Slide 9 - Pons Cross-Section: Upper Pons (light bg) Title: "Upper Pons: CN V (Trigeminal)" Cross-section diagram: - CN V main sensory nucleus (large, mid-lateral) - CN V motor nucleus (smaller, medial to sensory) - Mesencephalic nucleus of CN V (proprioception for jaw) - Spinal nucleus of CN V (pain/temp, extends to medulla) - MLF (medial longitudinal fasciculus) — paramedian - Corticospinal tracts (bilateral, basal pons) Key fact: "Jaw deviates TOWARD lesion side — ipsilateral lateral pterygoid is weak" ### Slide 10 - Pons Cross-Section: Middle Pons (light bg) Title: "Middle Pons: CN VI & VII" Cross-section with: - CN VI nucleus (floor of 4th ventricle — facial colliculus) - CN VII nucleus (lower pons — facial motor) - CN VII fibers loop around CN VI nucleus (internal genu) - MLF - PPRF (paramedian pontine reticular formation) — horizontal gaze center Key fact box: "The facial colliculus = CN VII fibers wrapping CN VI nucleus. A lesion here knocks out BOTH CN VI and CN VII ipsilaterally." ### Slide 11 - Pons Cross-Section: CN VIII Level (light bg) Title: "Lower Pons: CN VIII (Vestibulocochlear)" Diagram: - Cochlear nuclei (dorsal + ventral) — lateral - Vestibular nuclei (medial, superior, lateral, inferior) - Trapezoid body (auditory crossing fibers) - CN VIII enters at cerebellopontine angle (CP angle) Key fact: "CP Angle Tumor = Acoustic Neuroma (Vestibular Schwannoma) — compresses CN VII + VIII + sometimes CN V" ### Slide 12 - Pons Clinical Correlations (light bg) Title: "Pontine Syndromes — High Yield" Table: | Syndrome | Structures | Findings | | Millard-Gubler | CN VI + CN VII + corticospinal | Ipsilateral CN VI + VII palsy, contralateral hemiplegia | | Foville | CN VI + PPRF + corticospinal | Ipsilateral gaze palsy, contralateral hemiplegia | | Raymond | CN VI + corticospinal (no CN VII) | Ipsilateral lateral rectus palsy, contralateral hemiplegia | | Locked-in | Bilateral corticospinal + corticobulbar | Quadriplegia, anarthria; preserved vertical eye movements | Highlight box: "PPRF lesion = eyes deviate TOWARD the lesion (contralateral gaze palsy)" ### Slide 13 - Section Header: MEDULLA (dark bg) Large text: "MEDULLA" Subtitle: "CN IX, X, XI, XII Nuclei" Level label: "Open Medulla (Rostral) & Closed Medulla (Caudal)" ### Slide 14 - Open Medulla Cross-Section (light bg) Title: "Open Medulla (Rostral): CN IX, X, XI" Cross-section: - 4th ventricle (open, dorsal) - Nucleus ambiguus (motor for CN IX, X, XI) — lateral tegmentum - Dorsal motor nucleus of vagus (parasympathetic) — near floor of 4th ventricle - Nucleus tractus solitarius (NTS) — taste afferents for CN VII, IX, X - Inferior olivary nucleus — large oval, anteromedial - Spinothalamic tract — lateral - Sympathetic fibers (descending) — lateral tegmentum - Inferior cerebellar peduncle ### Slide 15 - Closed Medulla Cross-Section (light bg) Title: "Closed Medulla (Caudal): CN XII" Cross-section: - CN XII nucleus — paramedian (near midline) - CN XII fibers exit ANTERIORLY between pyramid and olive - Corticospinal tract (pyramid) — anterior - Medial lemniscus - Spinal nucleus of CN V (continues from pons) Key fact: "CN XII exits between the PYRAMID and the OLIVE — 'preolivary sulcus'" ### Slide 16 - Wallenberg Syndrome Deep Dive (light bg) Title: "Wallenberg Syndrome (Lateral Medullary Syndrome)" Large bold header: "PICA Occlusion" Two-column layout: LEFT — Structures damaged: - Nucleus ambiguus (CN IX, X) → Dysphagia, hoarseness, loss of gag - Vestibular nuclei → Vertigo, nystagmus - Spinothalamic tract → Contralateral pain/temp loss (body) - Spinal nucleus CN V → Ipsilateral facial pain/temp loss - Descending sympathetic → Ipsilateral Horner's syndrome - Inferior cerebellar peduncle → Ipsilateral ataxia/falling RIGHT — Clinical findings checklist: ✓ Dysphagia + hoarse voice (CN X) ✓ Vertigo + nystagmus ✓ Ipsilateral facial numbness (CN V nucleus) ✓ Contralateral body pain/temp loss (STT) ✓ Ipsilateral Horner's (ptosis, miosis, anhidrosis) ✓ Ipsilateral limb ataxia ✗ NO hemiplegia (pyramids spared) Memory hook box: "PICA = Pain Ipsilateral face, Contralateral body, Ataxia" ### Slide 17 - Medulla Clinical Correlations (light bg) Title: "Medullary Syndromes — High Yield" Table: | Syndrome | Location | Key Findings | | Wallenberg (Lateral medullary) | Lateral medulla, PICA | See slide 16 | | Medial medullary (Dejerine) | Medial medulla, ASA | Ipsilateral tongue deviation + contralateral hemiplegia + contralateral vibration/proprioception loss | | Hypoglossal hemiplegia alternans | CN XII + pyramid | Ipsilateral tongue deviation + contralateral UMN hemiplegia | ### Slide 18 - MLF and Gaze Pathways (light bg) Title: "Medial Longitudinal Fasciculus (MLF) — Internuclear Ophthalmoplegia" Diagram showing: - PPRF (horizontal gaze center, pons) - CN VI nucleus - MLF connecting CN VI nucleus to contralateral CN III nucleus - INO: lesion of MLF → ipsilateral adduction failure + contralateral nystagmus Key fact: "Bilateral INO in a young woman = Multiple Sclerosis until proven otherwise" "Unilateral INO in an elderly man = Brainstem vascular disease" ### Slide 19 - Complete Nuclei Summary Table (light bg) Title: "All Cranial Nerve Nuclei: Location Summary" Full table: | Nucleus | CN | Brainstem Level | Function | | Edinger-Westphal | III | Midbrain (SC level) | Pupil constriction, accommodation | | CN III nucleus | III | Midbrain (SC level) | Eye movement (SR, IR, MR, IO) | | CN IV nucleus | IV | Midbrain (IC level) | Superior oblique | | Mesencephalic V | V | Midbrain → upper pons | Proprioception jaw | | Main sensory V | V | Upper pons | Fine touch face | | Motor nucleus V | V | Upper pons | Muscles of mastication | | Spinal nucleus V | V | Pons → medulla | Pain/temp face | | CN VI nucleus | VI | Lower pons | Lateral rectus | | CN VII nucleus | VII | Lower pons | Facial muscles | | Superior salivatory | VII | Lower pons | Lacrimation, submandibular/sublingual salivation | | Cochlear nuclei | VIII | Lower pons | Hearing | | Vestibular nuclei | VIII | Lower pons/upper medulla | Balance | | CN IX nucleus (Amb) | IX | Open medulla | Stylopharyngeus | | Inferior salivatory | IX | Open medulla | Parotid salivation | | Nucleus ambiguus | IX, X, XI | Open medulla | Pharynx, larynx, palate | | Dorsal motor X | X | Open medulla | Parasympathetic viscera | | NTS | VII, IX, X | Open medulla/pons | Taste, visceral afferents | | CN XI (spinal) | XI | C1-C5 spinal cord | SCM, trapezius | | CN XII nucleus | XII | Closed medulla | Tongue | ### Slide 20 - Final Summary / Memory Hook Slide (dark bg) Title: "The Board Exam Cheat Sheet" 3 boxes: Box 1 (gold border): MIDBRAIN "CN III, IV — Weber, Benedikt — PCom aneurysm" Box 2 (blue border): PONS "CN V, VI, VII, VIII — Millard-Gubler — CP angle tumor — MLF/INO" Box 3 (teal border): MEDULLA "CN IX, X, XI, XII — Wallenberg (PICA) — Dejerine (ASA) — Jugular foramen syndromes" Bottom: "Nucleus Ambiguus = CN IX + X + XI motor | NTS = taste (VII, IX, X) | Dorsal Motor X = parasympathetics" ## Technical Notes - Use pptxgenjs (Node.js) — file: /home/daytona/workspace/cranial-nerves/create_brainstem_pptx.js - Run with: node /home/daytona/workspace/cranial-nerves/create_brainstem_pptx.js - For cross-section diagrams: use addShape() to draw circles, rectangles, and ellipses to simulate brainstem cross-sections. Use addText() for labels. Use addLine() or narrow rectangles for connector lines. - Make slides visually rich with shapes and color coding, not just text bullets - Output: /home/daytona/workspace/cranial-nerves/Brainstem_CrossSections.pptx Return the exact file path of the created PPTX.

general-purpose

Create two files for a medical board exam study resource on Cranial Nerves (CN I-XII): 1. A Python script that generates a PDF with 12-15 integrated clinical vignettes (FMGE/USMLE style) combining CN I-XII 2. Run the script to produce the PDF Save files to /home/daytona/workspace/cranial-nerves/ - Script: vignettes_script.py - Output PDF: CN_Clinical_Vignettes.pdf First create the directory: mkdir -p /home/daytona/workspace/cranial-nerves/ Use ReportLab for PDF generation (already installed). Do NOT run pip install. ## PDF Structure ### Cover Page Title: "Cranial Nerves I-XII: Integrated Clinical Vignettes" Subtitle: "FMGE | NEXT | USMLE Practice Cases" Style: dark blue background (#1a3a6b), white text, professional ### Format for Each Vignette - Vignette number and title (e.g., "Case 1: The Frustrated Chef") - Clinical scenario (3-5 sentences describing a real-sounding patient) - 4-option MCQ question - Answer + detailed explanation (2-4 sentences explaining the diagnosis and key board teaching point) - "Board Keywords" shaded box listing 3-5 exam-trigger words ### The 14 Vignettes (write these exactly): **Case 1: The Mountain Biker** A 28-year-old man is brought to the ER after a high-speed mountain bike crash. He struck his forehead on a rock. On examination, he is fully conscious and neurologically intact except that he cannot smell his wife's perfume or taste his food properly. CT shows a fracture through the cribriform plate. Q: Which cranial nerve is most likely injured? A) CN II B) CN I C) CN V1 D) CN VII Answer: B - CN I (Olfactory). The cribriform plate transmits CN I fibers from the nasal epithelium to the olfactory bulb. Fracture here shears these fibers, causing anosmia and secondary taste alteration (flavor perception requires olfaction). Taste proper — sweet, salty, bitter, sour — is mediated by CN VII, IX, X and is intact. Board Keywords: Cribriform plate fracture | Anosmia | Flavor vs. Taste | CN I **Case 2: The Ophthalmology Referral** A 35-year-old woman with a 1-year history of episodic right eye pain with eye movement and blurring of vision presents to neurology. Her visual acuity is 20/40 in the right eye and 20/20 in the left. When a flashlight is rapidly alternated between the eyes, both pupils appear to dilate when light is shone in the right eye. Q: What is the most likely diagnosis? A) CN III palsy B) Horner's syndrome C) Optic neuritis (CN II) with RAPD D) Retinal detachment Answer: C - Optic neuritis with a Relative Afferent Pupillary Defect (RAPD), also called Marcus Gunn Pupil. Pain with eye movement + subacute vision loss in a young woman is the classic presentation of optic neuritis associated with Multiple Sclerosis. The RAPD indicates an afferent (sensory) defect in the right CN II - both pupils dilate because the diseased optic nerve sends a weaker signal. Board Keywords: RAPD | Marcus Gunn | Optic neuritis | Multiple sclerosis | CN II | Swinging flashlight test **Case 3: The Thunderclap Headache** A 52-year-old hypertensive man presents to the ER with "the worst headache of my life" that began suddenly 2 hours ago. On examination, his right eyelid droops completely, his right eye is deviated down and out, and his right pupil is 7mm and non-reactive to light. The left eye is completely normal. Q: What is the most likely cause? A) Diabetic CN III neuropathy B) Posterior communicating artery aneurysm C) Midbrain infarct D) Myasthenia gravis Answer: B - PCom aneurysm. The key is the PUPIL-INVOLVED CN III palsy — the fixed dilated pupil indicates compression of the parasympathetic fibers that run on the outside of CN III. These fibers are spared in diabetic ischemic neuropathy (pupil-sparing). A thunderclap headache with pupil-involved CN III palsy is a ruptured or expanding PCom aneurysm until proven otherwise — neurosurgical emergency. Board Keywords: Pupil-involved CN III | PCom aneurysm | Down-and-out | Thunderclap headache | Surgical CN III **Case 4: The Reluctant Stair Climber** A 45-year-old woman comes in complaining that she keeps tripping going downstairs and has to tilt her head to the right to read. She noticed this after a minor head-on car collision 3 weeks ago. On exam, she has vertical diplopia that worsens when she looks down and toward her nose. She tilts her head to the LEFT. Q: Which nerve is injured and on which side? A) Left CN VI B) Right CN IV C) Left CN IV D) Right CN III Answer: C - Left CN IV (Trochlear). The superior oblique muscle (CN IV) depresses and intorts the eye. Left superior oblique palsy → vertical diplopia worst on downgaze (stairs, reading). The head tilts to the RIGHT (contralateral) to compensate. CN IV has the longest intracranial course and crosses the midline — it is uniquely vulnerable to shear injury from acceleration-deceleration trauma. Board Keywords: CN IV | Superior oblique | Head tilt away | Stair difficulty | Longest intracranial course | Vertical diplopia **Case 5: The Barber's Nightmare** A 68-year-old man describes sudden, lancinating, electric shock-like pain across the right side of his face, rating 10/10 in severity, lasting 2-3 seconds and triggered by shaving or a gust of wind. The pain occurs up to 50 times per day. Neurological examination is completely normal. Q: What is the first-line pharmacological treatment? A) Gabapentin B) Carbamazepine C) Amitriptyline D) Sumatriptan Answer: B - Carbamazepine is the first-line treatment for Trigeminal Neuralgia (Tic Douloureux). The clinical description is classic: lancinating, electric shock-like, unilateral facial pain in V2/V3 distribution triggered by light touch. The normal neurological exam distinguishes it from symptomatic trigeminal neuropathy (which has sensory loss). Microvascular decompression is surgical treatment for refractory cases. Board Keywords: Tic Douloureux | Carbamazepine | Lancinating unilateral face pain | Trigger zones | CN V | Microvascular decompression **Case 6: The Double Vision at Dinner** A 14-year-old boy presents with horizontal double vision when looking to the right. His left eye cannot abduct past midline. His pupils are equal and reactive. The rest of the exam is normal. MRI of the brain shows a pontine lesion. Q: Which structure is most likely affected? A) CN IV nucleus B) CN VI nucleus C) MLF D) PPRF Answer: B - CN VI nucleus (Abducens nucleus). The CN VI nucleus in the pons contains two populations of cells: (1) motor neurons to the ipsilateral lateral rectus, and (2) interneurons that cross via the MLF to the contralateral CN III nucleus for conjugate gaze. A CN VI nucleus lesion causes an IPSILATERAL GAZE PALSY (cannot look toward the side of the lesion), not just lateral rectus weakness. If only the lateral rectus nerve was affected, the other eye would compensate. Board Keywords: CN VI nucleus | Ipsilateral gaze palsy | PPRF | Pontine lesion | Horizontal gaze center **Case 7: The Bell's Palsy vs. Stroke Question** A 70-year-old man with hypertension and diabetes wakes up with right facial drooping. On exam: right nasolabial fold is flattened, right corner of mouth droops, but when asked to wrinkle his forehead or raise his eyebrows, he can do so bilaterally and symmetrically. He can close both eyes completely. Q: What is the most likely diagnosis and localization? A) Bell's Palsy (LMN, CN VII) B) Right MCA stroke (UMN) C) Left MCA stroke (UMN) D) Pontine hemorrhage Answer: C - LEFT MCA stroke (UMN facial palsy). Forehead SPARING is the key: the frontalis muscle receives bilateral cortical innervation, so a UMN lesion (cortex or internal capsule) spares forehead movement. The right facial droop means the left motor cortex is affected (contralateral), pointing to a left MCA territory infarct. Bell's palsy (LMN) affects ALL ipsilateral facial muscles INCLUDING the forehead. Board Keywords: Forehead sparing = UMN | Forehead involved = LMN (Bell's) | Contralateral cortex | Left MCA | CN VII UMN vs LMN **Case 8: The Concert Musician** A 32-year-old professional violinist presents with progressive right-sided hearing loss over 6 months, constant right-sided tinnitus, and episodes of true vertigo. On audiometry: right-sided sensorineural hearing loss. Weber test lateralizes to the LEFT ear. Rinne is positive (AC > BC) bilaterally but reduced on the right. MRI shows a 2.3 cm enhancing mass at the right cerebellopontine angle. Q: What is the most likely diagnosis and its genetic association? A) Meningioma, no association B) Vestibular Schwannoma, NF-2 C) Cholesteatoma, NF-1 D) Epidermoid cyst, no association Answer: B - Vestibular Schwannoma (Acoustic Neuroma), associated with Neurofibromatosis Type 2 (NF-2) when bilateral. It arises from Schwann cells of the vestibular division of CN VIII in the internal auditory canal and grows into the CP angle, compressing CN VIII (hearing loss, tinnitus, vertigo), then CN VII (facial weakness), then CN V. Weber lateralizes to the GOOD (left) ear in sensorineural hearing loss. Board Keywords: CP angle | Weber to good ear | SNHL | Acoustic neuroma | NF-2 = bilateral vestibular schwannomas | CN VIII **Case 9: The Swallowing Syncope** A 58-year-old woman describes recurrent episodes of passing out immediately after swallowing cold liquids. She also notices brief, severe pain deep in her right ear and throat at the moment of swallowing. Her neurological exam is normal between episodes. ECG during an episode shows asystole lasting 4 seconds. Q: What is the diagnosis? A) Vagal syncope B) Glossopharyngeal neuralgia with cardiac syncope C) Carotid sinus hypersensitivity D) Temporal lobe seizure Answer: B - Glossopharyngeal Neuralgia with cardiac syncope. CN IX carries the afferent limb of the carotid sinus reflex. Lancinating throat/ear pain on swallowing triggered by cold is pathognomonic of GPN. The reflex arc through CN IX → dorsal vagal nucleus → CN X → SA node can produce profound bradycardia or asystole, causing syncope. Treatment: carbamazepine first-line; surgical microvascular decompression for refractory cases. Board Keywords: GPN | Swallowing syncope | Asystole | CN IX carotid reflex | Carbamazepine | Microvascular decompression **Case 10: The Hoarse Surgeon** A 61-year-old man undergoes elective left carotid endarterectomy. Post-operatively, he is hoarse and has difficulty swallowing liquids (nasal regurgitation). On mirror laryngoscopy, the left vocal cord is immobile in the paramedian position. The uvula deviates to the RIGHT when he says "Ahh." Q: Which nerve was injured and what is the uvula deviation rule? A) Left RLN only; uvula toward lesion B) Left CN X (vagus); uvula away from lesion C) Left CN XII; uvula toward lesion D) Left CN XI; no uvula change Answer: B - Left CN X (Vagus nerve) injury. CN X controls the ipsilateral soft palate and vocal cord. Palatal weakness on the left means the right side pulls the uvula away (to the RIGHT) — uvula deviates AWAY from the side of the lesion. This is distinct from CN XII (tongue) which deviates TOWARD the lesion. The vocal cord palsy (hoarseness) confirms CN X, not RLN alone, is injured. Board Keywords: Uvula away from lesion (CN X) | Tongue toward lesion (CN XII) | Vagus nerve | Carotid endarterectomy complication | Vocal cord palsy **Case 11: The Post-Neck-Dissection Shoulder** A 54-year-old woman undergoes modified radical neck dissection for left-sided squamous cell carcinoma of the tonsil. Two weeks later, she cannot raise her left arm above 90 degrees and has visible winging of her left scapula. On exam, she has marked weakness of left shoulder shrug and cannot turn her head to the right against resistance. Q: Which nerve was damaged and what are its two motor targets? A) CN XII — genioglossus and hyoglossus B) CN XI — sternocleidomastoid and trapezius C) CN X — cricothyroid and thyroarytenoid D) Phrenic nerve — diaphragm Answer: B - CN XI (Spinal Accessory nerve), injured during neck dissection as it courses through the posterior triangle of the neck. It innervates: (1) Sternocleidomastoid — turns head to OPPOSITE side; tested by asking patient to turn chin away while examiner resists. (2) Trapezius — elevates shoulder; tested by asking patient to shrug against resistance. Scapular winging results from trapezius weakness. Board Keywords: CN XI | Spinal accessory | Neck dissection | SCM + trapezius | Scapular winging | Posterior triangle **Case 12: The ALS Tongue** A 62-year-old man presents with progressive slurring of speech and difficulty chewing over 8 months. On examination, his tongue at rest shows visible rhythmic quivering. When asked to protrude his tongue, it deviates to the RIGHT. He also has widespread upper motor neuron signs in his limbs (hyperreflexia, upgoing plantars). Q: Where is the lower motor neuron lesion for the tongue, and which disease combines UMN + LMN features? A) Right CN XII nucleus — Stroke B) Right CN XII — ALS (Amyotrophic Lateral Sclerosis) C) Left CN XII — ALS D) Left cortex — UMN stroke Answer: B - Right CN XII palsy in the context of ALS. Tongue deviates TOWARD the weak side (right). Fasciculations = LMN pathology (denervation). ALS is the only condition that produces simultaneous UMN (hyperreflexia, spasticity) and LMN (atrophy, fasciculations) signs. The combination of tongue fasciculations + hyperreflexia is essentially pathognomonic for ALS. Board Keywords: CN XII toward lesion | Fasciculations = LMN | ALS = UMN + LMN | Tongue atrophy | Hypoglossal nucleus **Case 13: The Four-Nerve Palsy** A 67-year-old man with a known right parotid gland tumor presents with progressive right-sided dysphagia, hoarseness, shoulder drop, and tongue deviation to the right. On examination: absent gag on the right, uvula deviates LEFT, right trapezius/SCM weakness, right tongue atrophy with deviation right on protrusion, and right ptosis with small right pupil (Horner's syndrome). Q: What is the syndrome and which space does the tumor involve? A) Vernet syndrome — jugular foramen B) Collet-Sicard syndrome — jugular foramen C) Villaret syndrome — retroparotid space D) Wallenberg syndrome — lateral medulla Answer: C - Villaret Syndrome. The retroparotid (retrostyloid) space contains CN IX, X, XI, XII AND the cervical sympathetic chain. Involvement of all four lower cranial nerves plus Horner's syndrome (sympathetic chain disruption) = Villaret. Compare: Vernet = CN IX+X+XI only (jugular foramen); Collet-Sicard = CN IX+X+XI+XII (without Horner's); Villaret = CN IX+X+XI+XII + Horner's (retroparotid). Board Keywords: Villaret | Retroparotid space | CN IX+X+XI+XII + Horner's | Parotid tumor | Sympathetic chain **Case 14: The Crossed Syndrome** A 71-year-old woman with atrial fibrillation (not anticoagulated) develops sudden onset of severe vertigo, vomiting, hoarseness, and inability to swallow. On examination: ipsilateral (left) facial numbness to pin-prick, ipsilateral Horner's syndrome, ipsilateral limb ataxia; contralateral (right) body loss of pain and temperature from the neck down. There is NO limb weakness and NO facial weakness (orbicularis intact). Q: What is the diagnosis and which artery is occluded? A) Left MCA stroke — middle cerebral artery B) Lateral medullary (Wallenberg) syndrome — left PICA occlusion C) Pontine hemorrhage — basilar artery D) Medial medullary syndrome — anterior spinal artery Answer: B - Wallenberg Syndrome, left PICA occlusion. The classic crossed sensory pattern: ipsilateral facial pain/temp loss (spinal nucleus CN V) + contralateral body pain/temp loss (crossed spinothalamic tract). Hoarseness + dysphagia = nucleus ambiguus (CN IX, X). Horner's = descending sympathetic fibers. Ataxia = inferior cerebellar peduncle. No weakness because the PYRAMIDS (corticospinal tract) are in the MEDIAL medulla and are SPARED. Board Keywords: Wallenberg | PICA | Crossed sensory | Ipsilateral Horner's | No hemiplegia | Nucleus ambiguus | Lateral medulla ### Design Notes - Professional blue/white theme (#1a3a6b headers) - Each case on its own page or clearly separated - Question in a shaded box - Answer section in a green-tinted box - Board keywords in a gold/yellow shaded box - Page numbers in footer - Running header: "CN I-XII Clinical Vignettes | FMGE/USMLE" Use ReportLab (already installed). Write the complete Python script to /home/daytona/workspace/cranial-nerves/vignettes_script.py and run it to produce /home/daytona/workspace/cranial-nerves/CN_Clinical_Vignettes.pdf Return the exact file path of the created PDF.

Reading File
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/cranial-nerves && echo "Directory created"

Running Command

mkdir -p /home/daytona/workspace/cranial-nerves/ && echo "Directory created"

Writing File

~/cranial-nerves/generate_cn_pdf.py

#!/usr/bin/env python3
"""
Cranial Nerves I-XII: Complete Board Review PDF Generator
For FMGE / NEXT / USMLE students
Uses ReportLab Platypus for professional formatting.
"""

import os
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, mm
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle,
    HRFlowable, KeepTogether
)
from reportlab.platypus.flowables import Flowable
from reportlab.pdfgen import canvas as rl_canvas
from reportlab.lib.colors import HexColor

# ─────────────────────────────────────────────
# COLOUR PALETTE
# ─────────────────────────────────────────────
DARK_BLUE   = HexColor("#1a3a6b")
MID_BLUE    = HexColor("#2563a8")
LIGHT_BLUE  = HexColor("#dce8f7")
ACCENT_BLUE = HexColor("#4a90d9")
YELLOW_HL   = HexColor("#fff8dc")
GRAY_LIGHT  = HexColor("#f4f4f4")
GRAY_MID    = HexColor("#d0d0d0")
GRAY_DARK   = HexColor("#555555")
WHITE       = colors.white
BLACK       = colors.black
ALT_ROW     = HexColor("#eaf2ff")
GREEN_LIGHT = HexColor("#e8f5e9")

PAGE_W, PAGE_H = A4
MARGIN = 18 * mm

# ─────────────────────────────────────────────
# PAGE TEMPLATE  (header stripe + footer)
# ─────────────────────────────────────────────
def make_page_template(canvas, doc):
    """Draw running header and footer on every page (except cover)."""
    canvas.saveState()
    page_num = doc.page

    if page_num > 1:
        # Top blue stripe
        canvas.setFillColor(DARK_BLUE)
        canvas.rect(0, PAGE_H - 28, PAGE_W, 28, fill=1, stroke=0)
        canvas.setFont("Helvetica-Bold", 9)
        canvas.setFillColor(WHITE)
        canvas.drawString(MARGIN, PAGE_H - 18, "Cranial Nerves I\u2013XII: Complete Board Review")
        canvas.drawRightString(PAGE_W - MARGIN, PAGE_H - 18,
                               "FMGE | NEXT | USMLE")

        # Bottom footer line
        canvas.setStrokeColor(DARK_BLUE)
        canvas.setLineWidth(1)
        canvas.line(MARGIN, 22, PAGE_W - MARGIN, 22)
        canvas.setFont("Helvetica", 8)
        canvas.setFillColor(DARK_BLUE)
        canvas.drawString(MARGIN, 10, "High-Yield Board Review Guide")
        canvas.drawRightString(PAGE_W - MARGIN, 10, f"Page {page_num}")

    canvas.restoreState()


# ─────────────────────────────────────────────
# STYLE FACTORY
# ─────────────────────────────────────────────
def build_styles():
    base = getSampleStyleSheet()

    styles = {
        "cover_title": ParagraphStyle("cover_title",
            fontName="Helvetica-Bold", fontSize=32, textColor=WHITE,
            alignment=TA_CENTER, spaceAfter=10, leading=38),

        "cover_subtitle": ParagraphStyle("cover_subtitle",
            fontName="Helvetica", fontSize=16, textColor=LIGHT_BLUE,
            alignment=TA_CENTER, spaceAfter=6, leading=22),

        "cover_tag": ParagraphStyle("cover_tag",
            fontName="Helvetica-Bold", fontSize=12, textColor=YELLOW_HL,
            alignment=TA_CENTER, spaceAfter=4),

        "section_banner": ParagraphStyle("section_banner",
            fontName="Helvetica-Bold", fontSize=13, textColor=WHITE,
            alignment=TA_LEFT, spaceAfter=4, leading=18),

        "nerve_title": ParagraphStyle("nerve_title",
            fontName="Helvetica-Bold", fontSize=18, textColor=DARK_BLUE,
            alignment=TA_LEFT, spaceAfter=4, leading=22),

        "nerve_subtitle": ParagraphStyle("nerve_subtitle",
            fontName="Helvetica", fontSize=11, textColor=MID_BLUE,
            alignment=TA_LEFT, spaceAfter=2, leading=14),

        "body": ParagraphStyle("body",
            fontName="Helvetica", fontSize=9.5, textColor=BLACK,
            alignment=TA_LEFT, spaceAfter=3, leading=14),

        "body_small": ParagraphStyle("body_small",
            fontName="Helvetica", fontSize=8.5, textColor=BLACK,
            alignment=TA_LEFT, spaceAfter=2, leading=12),

        "label_blue": ParagraphStyle("label_blue",
            fontName="Helvetica-Bold", fontSize=9, textColor=DARK_BLUE,
            alignment=TA_LEFT, spaceAfter=2, leading=12),

        "mono": ParagraphStyle("mono",
            fontName="Courier", fontSize=8, textColor=DARK_BLUE,
            alignment=TA_LEFT, spaceAfter=2, leading=11,
            leftIndent=6, rightIndent=6),

        "keyword_title": ParagraphStyle("keyword_title",
            fontName="Helvetica-Bold", fontSize=9, textColor=DARK_BLUE,
            alignment=TA_LEFT, spaceAfter=2),

        "keyword_body": ParagraphStyle("keyword_body",
            fontName="Helvetica", fontSize=9, textColor=BLACK,
            alignment=TA_LEFT, spaceAfter=2, leading=13),

        "tbl_hdr": ParagraphStyle("tbl_hdr",
            fontName="Helvetica-Bold", fontSize=8.5, textColor=WHITE,
            alignment=TA_CENTER, leading=11),

        "tbl_cell": ParagraphStyle("tbl_cell",
            fontName="Helvetica", fontSize=8, textColor=BLACK,
            alignment=TA_LEFT, leading=11),

        "tbl_cell_c": ParagraphStyle("tbl_cell_c",
            fontName="Helvetica", fontSize=8, textColor=BLACK,
            alignment=TA_CENTER, leading=11),

        "tbl_bold": ParagraphStyle("tbl_bold",
            fontName="Helvetica-Bold", fontSize=8, textColor=DARK_BLUE,
            alignment=TA_LEFT, leading=11),

        "page_title": ParagraphStyle("page_title",
            fontName="Helvetica-Bold", fontSize=14, textColor=WHITE,
            alignment=TA_LEFT, spaceAfter=2, leading=18),

        "syndrome_h": ParagraphStyle("syndrome_h",
            fontName="Helvetica-Bold", fontSize=11, textColor=DARK_BLUE,
            spaceAfter=6, leading=15),
    }
    return styles

S = build_styles()


# ─────────────────────────────────────────────
# HELPER FLOWABLES
# ─────────────────────────────────────────────
class ColorBox(Flowable):
    """A rectangle background box wrapping content lines."""
    def __init__(self, lines, bg_color, border_color, width, padding=6):
        super().__init__()
        self.lines = lines          # list of (text, style)
        self.bg    = bg_color
        self.border= border_color
        self.width = width
        self.padding = padding
        self._height = None

    def wrap(self, availW, availH):
        total_h = self.padding * 2
        for text, style in self.lines:
            p = Paragraph(text, style)
            w, h = p.wrap(self.width - self.padding*2, availH)
            total_h += h + 2
        self._height = total_h
        return (self.width, total_h)

    def draw(self):
        self.canv.setFillColor(self.bg)
        self.canv.setStrokeColor(self.border)
        self.canv.setLineWidth(1)
        self.canv.roundRect(0, 0, self.width, self._height, 4, fill=1, stroke=1)
        y = self._height - self.padding
        for text, style in self.lines:
            p = Paragraph(text, style)
            w, h = p.wrap(self.width - self.padding*2, 9999)
            y -= h
            p.drawOn(self.canv, self.padding, y)
            y -= 2


def section_banner(title, color=DARK_BLUE, width=None):
    """A full-width banner paragraph for section headers."""
    w = width or (PAGE_W - 2 * MARGIN)
    data = [[Paragraph(title, S["section_banner"])]]
    t = Table(data, colWidths=[w])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), color),
        ("TOPPADDING",    (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("LEFTPADDING",   (0, 0), (-1, -1), 10),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 10),
        ("ROUNDEDCORNERS", [4]),
    ]))
    return t


def nerve_header_box(cn_num, name, emoji, fiber_type, width=None):
    """Blue header box for each nerve page."""
    w = width or (PAGE_W - 2 * MARGIN)
    title_text = f"{emoji}  CN {cn_num} \u2013 {name}"
    data = [
        [Paragraph(title_text, S["nerve_title"])],
        [Paragraph(fiber_type, S["nerve_subtitle"])],
    ]
    t = Table(data, colWidths=[w])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), LIGHT_BLUE),
        ("TOPPADDING",    (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING",   (0, 0), (-1, -1), 10),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 10),
        ("BOX", (0, 0), (-1, -1), 1.5, DARK_BLUE),
    ]))
    return t


def two_col_table(headers, rows, col_widths, alt=True):
    """Generic table builder with alternating row colours."""
    hdr_cells = [Paragraph(h, S["tbl_hdr"]) for h in headers]
    data = [hdr_cells]
    for i, row in enumerate(rows):
        cells = []
        for j, cell in enumerate(row):
            style = S["tbl_bold"] if j == 0 else S["tbl_cell"]
            cells.append(Paragraph(str(cell), style))
        data.append(cells)

    t = Table(data, colWidths=col_widths, repeatRows=1)
    row_styles = [
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1),
         [WHITE, ALT_ROW] if alt else [WHITE]),
        ("GRID",      (0, 0), (-1, -1), 0.4, GRAY_MID),
        ("TOPPADDING",    (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING",   (0, 0), (-1, -1), 6),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 6),
        ("VALIGN",    (0, 0), (-1, -1), "TOP"),
    ]
    t.setStyle(TableStyle(row_styles))
    return t


def keyword_box(keywords_list, width=None):
    """Shaded yellow high-yield keyword box."""
    w = width or (PAGE_W - 2 * MARGIN)
    joined = "  \u2022  ".join(keywords_list)
    lines = [
        ("<b>HIGH-YIELD BOARD KEYWORDS</b>", S["keyword_title"]),
        (joined, S["keyword_body"]),
    ]
    return ColorBox(lines, YELLOW_HL, HexColor("#c8a000"), w, padding=8)


def pathway_box(lines_text, width=None):
    """Mono-spaced ASCII pathway diagram box."""
    w = width or (PAGE_W - 2 * MARGIN)
    content = [("<b>NERVE PATHWAY</b>", S["label_blue"])]
    for line in lines_text:
        content.append((line, S["mono"]))
    return ColorBox(content, HexColor("#f0f6ff"), ACCENT_BLUE, w, padding=6)


# ─────────────────────────────────────────────────────────────
# COVER PAGE (drawn directly on canvas for full design control)
# ─────────────────────────────────────────────────────────────
class CoverPage(Flowable):
    def __init__(self):
        super().__init__()
        self.width  = PAGE_W
        self.height = PAGE_H

    def wrap(self, aw, ah):
        return (PAGE_W, PAGE_H)

    def draw(self):
        c = self.canv

        # ── Background gradient simulation (two rects) ──
        c.setFillColor(DARK_BLUE)
        c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)

        c.setFillColor(MID_BLUE)
        c.rect(0, PAGE_H * 0.45, PAGE_W, PAGE_H * 0.55, fill=1, stroke=0)

        # ── White diagonal stripe ──
        p = c.beginPath()
        p.moveTo(0, PAGE_H * 0.44)
        p.lineTo(PAGE_W, PAGE_H * 0.48)
        p.lineTo(PAGE_W, PAGE_H * 0.44)
        p.lineTo(0, PAGE_H * 0.40)
        p.close()
        c.setFillColor(HexColor("#ffffff22"))
        c.drawPath(p, fill=1, stroke=0)

        # ── Top accent line ──
        c.setStrokeColor(ACCENT_BLUE)
        c.setLineWidth(4)
        c.line(MARGIN, PAGE_H - 12, PAGE_W - MARGIN, PAGE_H - 12)

        # ── Brain/nerve decorative circles ──
        c.setFillColor(HexColor("#ffffff08"))
        c.circle(PAGE_W * 0.82, PAGE_H * 0.72, 90, fill=1, stroke=0)
        c.circle(PAGE_W * 0.15, PAGE_H * 0.25, 60, fill=1, stroke=0)
        c.setFillColor(HexColor("#ffffff05"))
        c.circle(PAGE_W * 0.5, PAGE_H * 0.1, 130, fill=1, stroke=0)

        # ── Main Title ──
        c.setFont("Helvetica-Bold", 36)
        c.setFillColor(WHITE)
        title1 = "Cranial Nerves I\u2013XII"
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.62, title1)

        c.setFont("Helvetica-Bold", 22)
        c.setFillColor(LIGHT_BLUE)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.57, "Complete Board Review")

        # ── Horizontal rule ──
        c.setStrokeColor(ACCENT_BLUE)
        c.setLineWidth(2)
        c.line(PAGE_W * 0.2, PAGE_H * 0.545, PAGE_W * 0.8, PAGE_H * 0.545)

        # ── Subtitle / exam tags ──
        c.setFont("Helvetica-Bold", 15)
        c.setFillColor(YELLOW_HL)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.51, "FMGE  |  NEXT  |  USMLE  High-Yield Guide")

        # ── Feature bullets ──
        features = [
            "All 12 Cranial Nerves with Pathways & Clinical Correlations",
            "Major CN Syndromes: Vernet, Wallenberg, Weber, Benedikt & more",
            "Quick-Reference Summary Table  |  Board Keywords for Every Nerve",
        ]
        c.setFont("Helvetica", 11)
        c.setFillColor(LIGHT_BLUE)
        y = PAGE_H * 0.455
        for feat in features:
            c.drawCentredString(PAGE_W / 2, y, f"\u2713  {feat}")
            y -= 18

        # ── Bottom info band ──
        c.setFillColor(HexColor("#0f2547"))
        c.rect(0, 0, PAGE_W, PAGE_H * 0.12, fill=1, stroke=0)

        c.setFont("Helvetica-Bold", 11)
        c.setFillColor(ACCENT_BLUE)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.085,
                            "Anatomy  \u2022  Physiology  \u2022  Pathology  \u2022  Clinical Medicine")
        c.setFont("Helvetica", 9)
        c.setFillColor(GRAY_MID)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.055,
                            "Comprehensive review for medical licensing examinations")

        # ── Bottom accent line ──
        c.setStrokeColor(ACCENT_BLUE)
        c.setLineWidth(3)
        c.line(MARGIN, PAGE_H * 0.13, PAGE_W - MARGIN, PAGE_H * 0.13)


# ─────────────────────────────────────────────────────────────
# DATA: All 12 Cranial Nerves
# ─────────────────────────────────────────────────────────────
CN_DATA = [
    # ── CN I ──────────────────────────────────────────────
    {
        "num": "I",  "name": "Olfactory",  "emoji": "👃",
        "fiber": "Purely Sensory",
        "pathway": [
            "Olfactory epithelium (nasal mucosa)",
            "    |",
            "    v  Cribriform plate of ethmoid bone",
            "    |",
            "Olfactory bulb  -->  Olfactory tract",
            "    |",
            "    v  (no thalamic relay)",
            "    |",
            "Primary olfactory cortex (piriform cortex)",
        ],
        "origin": "Olfactory neuroepithelium (bipolar neurons — true CN I cells lie in nasal mucosa)",
        "exit":   "Cribriform plate of ethmoid bone (multiple foramina)",
        "target": "Olfactory bulb → olfactory tract → piriform/primary olfactory cortex",
        "clinical": [
            ("Anosmia (total loss of smell)",    "Cribriform plate fracture (head trauma), olfactory groove meningioma"),
            ("Hyposmia",                          "Viral URTI, zinc deficiency, early Parkinson's / Alzheimer's"),
            ("Foster Kennedy Syndrome",           "Ipsilateral anosmia + optic atrophy; contralateral papilledema — frontal lobe meningioma pressing on CN I & II"),
            ("Kallmann Syndrome",                 "Anosmia + hypogonadotropic hypogonadism (GnRH neuron migration failure)"),
            ("Parosmia / Phantosmia",             "Distorted smell / smell hallucinations — temporal lobe epilepsy aura"),
        ],
        "keywords": ["Anosmia", "Cribriform plate", "Foster Kennedy", "Kallmann syndrome",
                     "No thalamic relay", "Piriform cortex", "Only CN without thalamus"],
    },

    # ── CN II ──────────────────────────────────────────────
    {
        "num": "II",  "name": "Optic",  "emoji": "👁",
        "fiber": "Purely Sensory (special somatic afferent — technically a CNS tract)",
        "pathway": [
            "Retina (ganglion cell axons)",
            "    |",
            "    v  Optic disc  -->  Optic nerve",
            "    |",
            "Optic chiasm (nasal fibers cross)",
            "    |",
            "    v  Optic tract",
            "    |",
            "Lateral Geniculate Nucleus (LGN) of thalamus",
            "    |",
            "    v  Optic radiations",
            "    |",
            "Primary visual cortex (V1, calcarine sulcus, occipital lobe)",
        ],
        "origin": "Retinal ganglion cells",
        "exit":   "Optic canal (together with ophthalmic artery)",
        "target": "Optic chiasm → LGN → primary visual cortex (calcarine fissure)",
        "clinical": [
            ("Optic neuritis",                    "Painful monocular vision loss; RAPD (Marcus Gunn pupil); MS hallmark"),
            ("Central scotoma",                   "Lesion of optic nerve distal to disc"),
            ("Bitemporal hemianopsia",            "Optic chiasm compression (pituitary adenoma — most common)"),
            ("Homonymous hemianopsia",            "Optic tract / radiation / occipital cortex lesion"),
            ("RAPD (afferent pupil defect)",      "CN II lesion — swinging flashlight test — affected eye shows paradoxical dilation"),
            ("Papilledema",                       "Bilateral disc swelling from raised ICP — visual acuity PRESERVED early"),
            ("Leber hereditary optic neuropathy", "Mitochondrial mutation; painless bilateral vision loss in young men"),
        ],
        "keywords": ["RAPD / Marcus Gunn pupil", "Bitemporal hemianopsia = chiasm = pituitary adenoma",
                     "Optic canal", "CNS tract (myelinated by oligodendrocytes)", "LGN thalamus",
                     "Calcarine fissure V1", "Optic neuritis + MS"],
    },

    # ── CN III ──────────────────────────────────────────────
    {
        "num": "III",  "name": "Oculomotor",  "emoji": "🔄",
        "fiber": "Motor (GSE) + Parasympathetic (GVE — Edinger-Westphal nucleus)",
        "pathway": [
            "Oculomotor nucleus + Edinger-Westphal nucleus (midbrain, periaqueductal gray)",
            "    |",
            "    v  Exits midbrain between PCA and SCA",
            "    |",
            "Runs in roof of posterior communicating artery (PComm)",
            "    |",
            "    v  Cavernous sinus (lateral wall)",
            "    |",
            "Superior orbital fissure  -->  Orbit",
            "    |",
            "    Superior div: SR, levator palpebrae superioris",
            "    Inferior div: IR, MR, IO  + ciliary ganglion (pupil/lens)",
        ],
        "origin": "Oculomotor nucleus (GSE) + Edinger-Westphal nucleus (GVE) — midbrain at level of superior colliculus",
        "exit":   "Superior orbital fissure",
        "target": "SR, IR, MR, IO muscles; levator palpebrae; ciliary muscle; pupillary sphincter",
        "clinical": [
            ("'Down and out' eye + ptosis + mydriasis", "Complete CN III palsy — surgical cause (PComm aneurysm, herniation) compresses outer parasympathetic fibers first"),
            ("Diabetic CN III palsy ('medical')",       "Pupil SPARED — microvascular ischemia of inner motor fibers; outer parasympathetics intact"),
            ("Uncal (transtentorial) herniation",       "FIRST sign = ipsilateral dilated pupil (parasympathetic fibers on outer surface compressed)"),
            ("Parinaud syndrome",                       "Dorsal midbrain compression (pineal tumor) — upgaze palsy, light-near dissociation"),
            ("Adie's (tonic) pupil",                    "Ciliary ganglion damage — dilated pupil, slow light reflex, accommodates poorly"),
        ],
        "keywords": ["Down-and-out + ptosis + mydriasis", "PComm aneurysm = pupil involved",
                     "Diabetic CN III = pupil spared", "Edinger-Westphal = parasympathetic",
                     "Superior orbital fissure", "Herniation earliest sign = blown pupil",
                     "SR/IR/MR/IO + levator palpebrae"],
    },

    # ── CN IV ──────────────────────────────────────────────
    {
        "num": "IV",  "name": "Trochlear",  "emoji": "🔭",
        "fiber": "Purely Motor (GSE)",
        "pathway": [
            "Trochlear nucleus (midbrain, inferior colliculus level, contralateral)",
            "    |",
            "    v  DECUSSATES in anterior medullary velum",
            "    |",
            "Exits DORSAL surface of brainstem (only CN to do so)",
            "    |",
            "    v  Longest intracranial course; wraps around midbrain",
            "    |",
            "Cavernous sinus (lateral wall)  -->  Superior orbital fissure",
            "    |",
            "Superior oblique muscle (down + intorsion movement)",
        ],
        "origin": "Trochlear nucleus — midbrain (inferior colliculus); CROSSED — right nucleus → left SO",
        "exit":   "Superior orbital fissure",
        "target": "Superior oblique muscle (depresses and intorts the eye)",
        "clinical": [
            ("Head tilt (compensatory)",          "CN IV palsy — patient tilts head AWAY from lesion (toward opposite shoulder) to reduce diplopia"),
            ("Vertical diplopia + worse on stairs", "Classic CN IV palsy: can't look down-and-in; difficulty descending stairs"),
            ("Bilateral CN IV palsy",             "Trauma to dorsal midbrain — bilateral superior oblique weakness"),
            ("Skew deviation",                    "Hypertropia — one eye higher; distinguish from CN IV palsy with Bielschowsky test"),
            ("Trochlear nucleus vs nerve lesion", "Nucleus lesion = contralateral SO palsy (due to decussation)"),
        ],
        "keywords": ["Longest intracranial course", "Only CN exiting DORSAL brainstem",
                     "Superior oblique = depression + intorsion", "Head tilt AWAY from lesion",
                     "Difficulty going downstairs", "Contralateral nucleus lesion",
                     "Most common CN injured in closed head trauma"],
    },

    # ── CN V ──────────────────────────────────────────────
    {
        "num": "V",  "name": "Trigeminal",  "emoji": "🦷",
        "fiber": "Mixed: Sensory (GSA — V1/V2/V3) + Motor (SVE — V3 only, masticatory muscles)",
        "pathway": [
            "Trigeminal ganglion (Gasserian / semilunar ganglion) on petrous apex",
            "    |",
            "    +-- V1 Ophthalmic  -->  Superior orbital fissure",
            "    |       (forehead, cornea, nose tip, dura)",
            "    |",
            "    +-- V2 Maxillary   -->  Foramen rotundum --> pterygopalatine fossa",
            "    |       (cheek, upper lip, upper teeth, hard palate)",
            "    |",
            "    +-- V3 Trigeminal  -->  Foramen ovale",
            "            (lower face, lower teeth, jaw, TMJ, ant 2/3 tongue GENERAL sensation)",
            "            Motor: masseter, temporalis, pterygoids, tensor tympani, tensor veli palatini",
            "    |",
            "Nuclei: Mesencephalic (proprioception), Main sensory (fine touch),",
            "        Spinal nucleus (pain/temp), Motor nucleus (chewing)",
        ],
        "origin": "Main sensory nucleus (pons), Spinal nucleus (pons→medulla→C2), Mesencephalic nucleus, Motor nucleus (pons)",
        "exit":   "V1: Superior orbital fissure | V2: Foramen rotundum | V3: Foramen ovale",
        "target": "Facial sensation (3 divisions) + chewing muscles (V3 motor)",
        "clinical": [
            ("Trigeminal neuralgia (tic douloureux)", "Electric shock-like pain V2 > V3 distribution; trigger: eating, talking; SCA compression most common"),
            ("Jaw deviation toward lesion",           "Motor V3 lesion — pterygoids of opposite side unopposed, jaw pushed toward weak side"),
            ("Corneal reflex",                        "Afferent = V1 (nasociliary); efferent = CN VII; tests V1 and CN VII integrity"),
            ("Herpes zoster (shingles)",              "V1 most common CN division affected: Hutchinson's sign (tip of nose) = nasociliary = high risk of keratitis"),
            ("Cavernous sinus syndrome",              "V1 + V2 involved (not V3); + CN III, IV, VI, and sympathetics"),
            ("Trigeminal schwannoma",                 "Foramen ovale / Meckel's cave mass; facial numbness + masseter wasting"),
        ],
        "keywords": ["V1=SOF, V2=foramen rotundum, V3=foramen ovale",
                     "Jaw toward lesion (motor V3)", "Tic douloureux = SCA compression",
                     "Corneal reflex afferent = V1", "V3 = ant 2/3 tongue GENERAL sensation",
                     "Hutchinson's sign = V1 zoster = corneal risk",
                     "Mesencephalic nucleus = only CNS proprioceptive nucleus"],
    },

    # ── CN VI ──────────────────────────────────────────────
    {
        "num": "VI",  "name": "Abducens",  "emoji": "↔",
        "fiber": "Purely Motor (GSE)",
        "pathway": [
            "Abducens nucleus (pons, floor of 4th ventricle)",
            "    |",
            "    v  Long intracranial course anteriorly",
            "    |",
            "Exits pons at pontomedullary junction",
            "    |",
            "    v  Ascends along clivus, pierces dura",
            "    |",
            "Cavernous sinus (runs INSIDE sinus — most medial)  -->  Superior orbital fissure",
            "    |",
            "Lateral rectus muscle (sole function: ABduction)",
        ],
        "origin": "Abducens nucleus — pons (floor of 4th ventricle)",
        "exit":   "Superior orbital fissure",
        "target": "Lateral rectus muscle (ABduction = lateral gaze)",
        "clinical": [
            ("Esotropia ('crossed eye')",         "CN VI palsy — lateral rectus weak — eye turns inward (medially deviated)"),
            ("False localizing sign",             "Raised ICP stretches CN VI over petrous ridge — palsy without pontine lesion"),
            ("Diplopia on lateral gaze",          "Hallmark — unable to abduct the eye; horizontal diplopia, worse at distance"),
            ("Wernicke's encephalopathy",         "CN VI palsy + nystagmus + ataxia + confusion — thiamine deficiency"),
            ("Cavernous sinus thrombosis",        "CN VI (most medial) affected first among CN III/IV/VI; + V1, V2, Horner's"),
            ("Millard-Gubler syndrome",           "Pontine infarct: ipsilateral CN VI + VII palsy + contralateral hemiplegia"),
            ("Foville syndrome",                  "Ipsilateral gaze palsy + ipsilateral CN VII + contralateral hemiplegia (PPRF involvement)"),
        ],
        "keywords": ["Esotropia = CN VI palsy", "False localizing sign for raised ICP",
                     "Longest intracranial course (clinically)", "CN VI runs INSIDE cavernous sinus",
                     "Lateral rectus = only muscle", "Millard-Gubler",
                     "Wernicke's = CN VI + nystagmus + ataxia"],
    },

    # ── CN VII ──────────────────────────────────────────────
    {
        "num": "VII",  "name": "Facial",  "emoji": "😊",
        "fiber": "Mixed: Motor (SVE — facial expression) + Sensory (SVA — taste ant 2/3 tongue; GSA — EAC) + Parasympathetic (GVE — lacrimal, submandibular, sublingual glands)",
        "pathway": [
            "Facial motor nucleus (pons)  +  Superior salivatory nucleus",
            "    |",
            "    v  Enters internal acoustic meatus (with CN VIII)",
            "    |",
            "Facial canal (petrous temporal bone)",
            "    |",
            "    +-- Greater petrosal nerve (parasym.)  -->  lacrimal, nasal, palate glands",
            "    |",
            "    +-- Nerve to stapedius (stapedius muscle reflex)",
            "    |",
            "    +-- Chorda tympani  -->  submandibular ganglion  -->  sublingual & submandibular glands",
            "    |       ALSO: taste ant 2/3 tongue (joins lingual nerve)",
            "    |",
            "    v  Stylomastoid foramen (exits skull)",
            "    |",
            "Parotid gland (divides into temporal, zygomatic, buccal, marginal mandibular, cervical)",
        ],
        "origin": "Facial motor nucleus (SVE), Superior salivatory nucleus (GVE), Nucleus tractus solitarius (SVA taste), CN VII sensory ganglion = geniculate ganglion",
        "exit":   "Stylomastoid foramen",
        "target": "All muscles of facial expression; stapedius; posterior digastric; stylohyoid; lacrimal/salivary glands; taste ant 2/3 tongue",
        "clinical": [
            ("Bell's palsy (LMN)",                "Complete ipsilateral facial weakness including forehead; viral (HSV-1); 80% recover"),
            ("UMN facial palsy (forehead sparing)", "Forehead SPARED — bilateral cortical representation of forehead; stroke, tumour above pons"),
            ("Hyperacusis",                       "Stapedius muscle paralysed — cannot dampen vibrations — loud sounds painful"),
            ("Loss of taste ant 2/3 tongue",      "Chorda tympani involvement (lesion proximal to its departure from facial canal)"),
            ("Ramsay Hunt syndrome",              "Herpes zoster reactivation in geniculate ganglion: ear pain, vesicles in EAC/auricle, ipsilateral facial palsy, hearing loss"),
            ("Crocodile tears (Bogorad syndrome)", "Aberrant regeneration — salivatory fibers regrow to lacrimal gland — tearing while eating"),
            ("Hemifacial spasm",                  "Vascular compression of CN VII at REZ; involuntary facial contractions"),
        ],
        "keywords": ["Bell's palsy = LMN = forehead involved", "UMN palsy = forehead SPARED",
                     "Hyperacusis = stapedius", "Chorda tympani = taste + submandibular",
                     "Geniculate ganglion = Ramsay Hunt zoster", "Stylomastoid foramen",
                     "Crocodile tears = aberrant regeneration", "Greatest petrosal = lacrimal"],
    },

    # ── CN VIII ──────────────────────────────────────────────
    {
        "num": "VIII",  "name": "Vestibulocochlear",  "emoji": "👂",
        "fiber": "Purely Sensory (SSA — special somatic afferent): Cochlear division (hearing) + Vestibular division (balance)",
        "pathway": [
            "COCHLEAR DIVISION:",
            "    Organ of Corti (inner hair cells) --> spiral ganglion (CN VIII bipolar neurons)",
            "    --> cochlear nerve --> internal acoustic meatus",
            "    --> cochlear nuclei (dorsal + ventral, pontomedullary junction)",
            "    --> bilateral superior olivary nuclei --> inferior colliculi --> MGB thalamus --> A1 cortex",
            "",
            "VESTIBULAR DIVISION:",
            "    Semicircular canals + utricle + saccule --> vestibular (Scarpa's) ganglion",
            "    --> vestibular nerve --> internal acoustic meatus",
            "    --> vestibular nuclei (pons/medulla) --> cerebellum, VOR, spinal cord",
        ],
        "origin": "Spiral ganglion (cochlear) + Scarpa's ganglion (vestibular)",
        "exit":   "Internal acoustic meatus (with CN VII, labyrinthine artery)",
        "target": "Cochlear nuclei → auditory cortex (hearing); Vestibular nuclei → cerebellum/VOR (balance)",
        "clinical": [
            ("Sensorineural hearing loss (SNHL)",  "Weber lateralizes to GOOD ear; Rinne: AC > BC (both reduced). Causes: acoustic neuroma, aminoglycosides, noise, age"),
            ("Conductive hearing loss (CHL)",      "Weber lateralizes to AFFECTED ear; Rinne: BC > AC. Causes: otosclerosis, wax, effusion"),
            ("Acoustic neuroma (schwannoma)",      "Unilateral SNHL + tinnitus + imbalance; arise from Schwann cells of vestibular portion; NF-2 = bilateral"),
            ("NF-2",                               "Bilateral acoustic neuromas pathognomonic; MERGE mutation; meningiomas + ependymomas also"),
            ("Vestibular neuritis / labyrinthitis","Acute vertigo, N/V, post-viral; horizontal nystagmus toward opposite side"),
            ("BPPV",                               "Posterior SCC most common; canalith repositioning; positive Dix-Hallpike"),
            ("Meniere's disease",                   "Endolymphatic hydrops; triad: episodic vertigo + fluctuating SNHL + tinnitus"),
        ],
        "keywords": ["Weber to good ear = SNHL", "Weber to bad ear = CHL",
                     "Acoustic neuroma = vestibular schwannoma", "NF-2 = bilateral acoustic neuromas",
                     "Internal acoustic meatus", "Aminoglycosides = cochleotoxic + vestibulotoxic",
                     "Meniere's = endolymphatic hydrops", "BPPV = Dix-Hallpike + Epley"],
    },

    # ── CN IX ──────────────────────────────────────────────
    {
        "num": "IX",  "name": "Glossopharyngeal",  "emoji": "🗣",
        "fiber": "Mixed: Motor (SVE — stylopharyngeus) + Sensory (SVA taste post 1/3 tongue; GVA carotid body/sinus; GSA EAC) + Parasympathetic (GVE — parotid gland via inferior salivatory nucleus)",
        "pathway": [
            "Nucleus ambiguus (motor: stylopharyngeus)",
            "Inferior salivatory nucleus (parasym: otic ganglion -> parotid)",
            "Nucleus tractus solitarius (taste + carotid body/sinus afferents)",
            "    |",
            "    v  Exits lateral medulla as rootlets",
            "    |",
            "Jugular foramen (with CN X and CN XI)",
            "    |",
            "    +-- Tympanic branch (Jacobson's nerve)  -->  middle ear, tympanic plexus",
            "    |       --> lesser petrosal nerve  -->  otic ganglion  -->  parotid gland",
            "    |",
            "    +-- Carotid sinus nerve  -->  carotid sinus + carotid body",
            "    |",
            "    +-- Stylopharyngeus muscle (only motor target)",
            "    |",
            "    v  Posterior 1/3 tongue (taste + general sensation)",
            "    v  Oropharynx, tonsils (general sensation)",
        ],
        "origin": "Nucleus ambiguus (SVE), Inferior salivatory nucleus (GVE), NTS (SVA/GVA), Spinal nucleus CN V (GSA)",
        "exit":   "Jugular foramen",
        "target": "Stylopharyngeus; parotid gland; taste + sensation post 1/3 tongue; carotid sinus/body; gag reflex afferent arm",
        "clinical": [
            ("Gag reflex (afferent arm)",         "CN IX afferent + CN X efferent; absent gag = CN IX or X lesion"),
            ("Carotid sinus hypersensitivity",    "Exaggerated carotid sinus reflex via CN IX -> NTS -> CN X -> bradycardia + hypotension; syncope on neck compression"),
            ("Glossopharyngeal neuralgia",        "Severe lancinating pain in throat/tongue/ear triggered by swallowing; can cause syncope via vagal activation"),
            ("Jugular foramen syndrome (Vernet)", "CN IX, X, XI lesion — dysphagia, hoarseness, shoulder drop"),
            ("Glomus jugulare tumour",            "Paraganglioma at jugular foramen; pulsatile tinnitus, hearing loss, lower CN palsies"),
            ("Parotid gland innervation",         "Parasympathetic via lesser petrosal nerve → otic ganglion (ear to parotid nerve mnemonic)"),
        ],
        "keywords": ["Gag reflex AFFERENT = CN IX", "Carotid sinus reflex via CN IX",
                     "Glossopharyngeal neuralgia + syncope", "Jugular foramen with X and XI",
                     "Only motor = stylopharyngeus", "Jacobson's nerve = tympanic branch",
                     "Lesser petrosal nerve = parotid", "Otic ganglion"],
    },

    # ── CN X ──────────────────────────────────────────────
    {
        "num": "X",  "name": "Vagus",  "emoji": "🫀",
        "fiber": "Mixed: Motor (SVE — pharynx/larynx; GVE — thoracic/abdominal viscera) + Sensory (SVA taste epiglottis; GVA visceral; GSA EAC)",
        "pathway": [
            "Nucleus ambiguus (SVE: soft palate, pharynx, larynx)",
            "Dorsal motor nucleus of vagus (GVE: parasympathetics to thorax/abdomen up to splenic flexure)",
            "Nucleus tractus solitarius (SVA + GVA afferents)",
            "    |",
            "    v  Exits lateral medulla below CN IX",
            "    |",
            "Jugular foramen",
            "    |",
            "    +-- Superior laryngeal nerve  -->  cricothyroid (external branch)",
            "    |                                  sensation above vocal cords (internal branch)",
            "    |",
            "    +-- Recurrent laryngeal nerve (RLN):",
            "    |       RIGHT RLN: loops around right subclavian artery",
            "    |       LEFT RLN: longer course, loops under aortic arch (ductus arteriosus)",
            "    |",
            "    v  Cardiac branches, pulmonary plexus, oesophageal plexus,",
            "       celiac plexus, GI tract to splenic flexure",
        ],
        "origin": "Nucleus ambiguus (SVE), Dorsal motor nucleus (GVE), NTS (SVA/GVA), Spinal V nucleus (GSA)",
        "exit":   "Jugular foramen",
        "target": "Pharynx, larynx (all muscles except stylopharyngeus and tensor veli palatini); heart, lungs, GI to splenic flexure",
        "clinical": [
            ("Uvula deviates AWAY from lesion",   "CN X/nucleus ambiguus lesion — unaffected palate elevates higher, pushing uvula to opposite side"),
            ("Left RLN palsy",                    "Aortic arch aneurysm, lung cancer (left hilar), cardiac surgery, mediastinal tumour — hoarseness"),
            ("Right RLN palsy",                   "Right subclavian aneurysm, apical lung tumor, right thyroid surgery"),
            ("Wallenberg (lateral medullary) syndrome", "PICA occlusion: dysphagia, hoarseness, ipsilateral Horner's, ipsilateral face pain/temp loss, contralateral body pain/temp loss, vertigo, nystagmus"),
            ("Vasovagal syncope",                 "Excessive vagal tone — bradycardia + vasodilation → syncope; triggered by pain, emotion"),
            ("Hoarseness from CN X lesion",       "All intrinsic laryngeal muscles except cricothyroid innervated by RLN (branch of CN X)"),
        ],
        "keywords": ["Uvula away from lesion", "Left RLN = aortic aneurysm / lung CA",
                     "Wallenberg = PICA = lateral medulla", "Dorsal motor nucleus = preganglionic parasympathetics",
                     "Nucleus ambiguus = pharynx/larynx motor", "Splenic flexure = distal parasympathetic limit",
                     "Hoarseness = RLN", "Vasovagal via CN X"],
    },

    # ── CN XI ──────────────────────────────────────────────
    {
        "num": "XI",  "name": "Spinal Accessory",  "emoji": "💪",
        "fiber": "Purely Motor (SVE — but largely considered GSE for SCM and trapezius)",
        "pathway": [
            "CRANIAL ROOT (minor): Nucleus ambiguus caudal part",
            "    |  (Joins CN X briefly, supplies laryngeal muscles via vagus)",
            "    |",
            "SPINAL ROOT (major): Anterior horn cells C1-C5/6",
            "    |",
            "    v  Ascends through foramen magnum",
            "    |",
            "Joins cranial root briefly -> exits via Jugular foramen",
            "    |",
            "    v  Descends in posterior triangle of neck",
            "    |",
            "Sternocleidomastoid (SCM)  -->  turns head to OPPOSITE side",
            "Trapezius  -->  elevates, retracts, rotates scapula; shoulder shrug",
        ],
        "origin": "Spinal root: C1–C5/6 anterior horn (main); Cranial root: nucleus ambiguus caudal (minor)",
        "exit":   "Jugular foramen",
        "target": "SCM muscle + Trapezius muscle",
        "clinical": [
            ("Neck dissection injury",            "Most common iatrogenic CN XI injury — posterior triangle surgery — shoulder drop + weak shoulder shrug"),
            ("Shoulder drop / winging of scapula","CN XI lesion — trapezius weakness — inferior angle of scapula wings outward on arm abduction"),
            ("SCM palsy",                         "Cannot turn head to OPPOSITE side; chin points toward side of lesion"),
            ("Vernet syndrome",                   "CN IX, X, XI at jugular foramen — dysphagia, hoarseness, shoulder drop"),
            ("Collet-Sicard syndrome",            "CN IX, X, XI, XII — jugular foramen + hypoglossal canal — above + tongue deviation"),
            ("Torticollis",                       "SCM spasm/hypertrophy — head tilted toward lesion side, chin rotated away"),
        ],
        "keywords": ["Spinal root = C1–C5/6 = MAIN functional component", "SCM: turns head CONTRALATERAL",
                     "Trapezius: shoulder shrug", "Neck dissection = most common injury",
                     "Jugular foramen with IX and X", "Shoulder drop = trapezius",
                     "Vernet = IX, X, XI", "Scapular winging = trapezius (CN XI) vs serratus anterior (long thoracic)"],
    },

    # ── CN XII ──────────────────────────────────────────────
    {
        "num": "XII",  "name": "Hypoglossal",  "emoji": "👅",
        "fiber": "Purely Motor (GSE — all intrinsic and most extrinsic tongue muscles)",
        "pathway": [
            "Hypoglossal nucleus (medulla, floor of 4th ventricle, near midline)",
            "    |",
            "    v  Exits medulla as rootlets in pre-olivary sulcus",
            "    |",
            "Hypoglossal canal (anterior condylar canal)",
            "    |",
            "    v  Loops around occipital condyle, enters neck",
            "    |",
            "Passes lateral to hyoglossus, medial to mylohyoid",
            "    |",
            "All intrinsic tongue muscles (longitudinal, vertical, transverse)",
            "Extrinsic: genioglossus, hyoglossus, styloglossus",
            "(Palatoglossus = CN X/XI, NOT CN XII)",
        ],
        "origin": "Hypoglossal nucleus — medulla (near midline, floor of 4th ventricle)",
        "exit":   "Hypoglossal canal (anterior condylar canal)",
        "target": "All tongue muscles EXCEPT palatoglossus (CN X)",
        "clinical": [
            ("Tongue deviates TOWARD lesion (LMN)", "LMN/nuclear/nerve lesion — ipsilateral genioglossus weak — tongue pushed toward weak side on protrusion"),
            ("Tongue deviates AWAY from lesion (UMN)", "Contralateral UMN lesion — tongue deviates away from the cortical lesion"),
            ("Tongue fasciculations + atrophy",   "LMN lesion — ALS (motor neuron disease) hallmark: wasting + fasciculations"),
            ("Collet-Sicard syndrome",            "CN IX, X, XI, XII — hypoglossal canal + jugular foramen involvement — skull base tumour"),
            ("Villaret syndrome",                 "CN IX, X, XI, XII + Horner's — retroparotid/retropharyngeal space"),
            ("Hypoglossal canal mass",            "Condylar meningioma, metastasis, chordoma — CN XII palsy"),
            ("Ansa cervicalis",                   "C1 fibers hitch-hike with CN XII briefly — supply thyrohyoid and geniohyoid"),
        ],
        "keywords": ["Tongue toward lesion = LMN", "Tongue away = UMN (contralateral cortex)",
                     "Hypoglossal canal", "Fasciculations + atrophy = ALS",
                     "Palatoglossus = CN X (not XII)", "Collet-Sicard = XII + IX/X/XI",
                     "Ansa cervicalis hitch-hikes with CN XII", "Genioglossus = main protrusor"],
    },
]


# ─────────────────────────────────────────────────────────────
# CN SYNDROMES TABLE DATA
# ─────────────────────────────────────────────────────────────
SYNDROMES = [
    ("Vernet",          "IX, X, XI",              "Jugular foramen",
     "Glomus jugulare / basal skull fracture",
     "Dysphagia, hoarseness, shoulder drop (trapezius weakness)"),

    ("Collet-Sicard",   "IX, X, XI, XII",          "Jugular foramen + hypoglossal canal",
     "Skull base tumour (glomus, chordoma, meningioma)",
     "Above + tongue deviation toward lesion (CN XII)"),

    ("Villaret",        "IX, X, XI, XII + Horner's","Retroparotid / retropharyngeal space",
     "Parotid tumour, carotid dissection, retropharyngeal mass",
     "Above + ipsilateral Horner's syndrome (sympathetic chain)"),

    ("Wallenberg",      "CN IX, X nuclei + tracts + SNRT","Lateral medulla (PICA territory)",
     "PICA occlusion (posterior inferior cerebellar artery)",
     "Dysphagia, hoarseness, ipsilateral Horner's + face pain/temp loss, contralateral body pain/temp loss, vertigo, nystagmus, hiccups"),

    ("Foster Kennedy",  "CN I, II",                "Frontal lobe / olfactory groove",
     "Frontal meningioma, olfactory groove meningioma",
     "Ipsilateral anosmia + optic atrophy (direct compression); contralateral papilledema (raised ICP)"),

    ("Weber",           "CN III + corticospinal tract","Midbrain (cerebral peduncle, ventral)",
     "PCA occlusion, midbrain infarct, TB granuloma",
     "Ipsilateral CN III palsy (down-out-ptosis-mydriasis) + contralateral hemiplegia"),

    ("Benedikt",        "CN III + red nucleus + dentatorubrothalamic tract","Midbrain tegmentum",
     "PCA branch occlusion, midbrain tumour",
     "Ipsilateral CN III palsy + contralateral tremor (rubrospinal), ataxia (dentate output)"),

    ("Millard-Gubler",  "CN VI, VII + corticospinal tract","Ventral pons",
     "Pontine infarct, pontine glioma",
     "Ipsilateral CN VI palsy (esotropia) + CN VII palsy (facial weakness) + contralateral hemiplegia"),

    ("Foville",         "CN VI, VII + PPRF + corticospinal","Dorsal/tegmental pons",
     "Pontine infarct",
     "Ipsilateral conjugate gaze palsy (PPRF) + CN VII palsy + contralateral hemiplegia"),

    ("Parinaud",        "Dorsal midbrain nuclei (CN III related)","Dorsal midbrain / superior colliculus",
     "Pineal tumour, hydrocephalus, MS, stroke",
     "Upgaze palsy, convergence retraction nystagmus, light-near dissociation, eyelid retraction (Collier sign)"),
]


# ─────────────────────────────────────────────────────────────
# SUMMARY TABLE DATA
# ─────────────────────────────────────────────────────────────
SUMMARY_TABLE = [
    ("I",    "Olfactory",        "Sensory",          "Cribriform plate",
     "Smell",
     "Anosmia, Foster Kennedy, Kallmann"),

    ("II",   "Optic",            "Sensory",          "Optic canal",
     "Vision",
     "RAPD, bitemporal hemianopsia, papilledema"),

    ("III",  "Oculomotor",       "Motor + Parasym",  "Sup orbital fissure",
     "SR, IR, MR, IO, levator; pupil constriction",
     "Down-and-out, ptosis, mydriasis, PComm aneurysm"),

    ("IV",   "Trochlear",        "Motor",            "Sup orbital fissure",
     "Superior oblique (down + intorsion)",
     "Head tilt away, longest intracranial course, stairs"),

    ("V",    "Trigeminal",       "Sensory + Motor",  "V1: SOF; V2: for. rotundum; V3: for. ovale",
     "Face sensation; chewing (V3)",
     "Tic douloureux, jaw to lesion, corneal reflex afferent"),

    ("VI",   "Abducens",         "Motor",            "Sup orbital fissure",
     "Lateral rectus (abduction)",
     "Esotropia, false localizing sign, raised ICP"),

    ("VII",  "Facial",           "Motor+Sensory+Para","Stylomastoid foramen",
     "Facial expression; taste ant 2/3; lacrimation; salivation",
     "Bell's palsy, UMN forehead spared, hyperacusis, chorda tympani"),

    ("VIII", "Vestibulocochlear","Sensory",          "Internal acoustic meatus",
     "Hearing + balance",
     "Weber to good ear (SNHL), acoustic neuroma, NF-2"),

    ("IX",   "Glossopharyngeal", "Mixed",            "Jugular foramen",
     "Taste + sensation post 1/3 tongue; gag afferent; parotid",
     "Gag afferent, carotid sinus reflex, neuralgia + syncope"),

    ("X",    "Vagus",            "Mixed",            "Jugular foramen",
     "Palate, pharynx, larynx; autonomics to splenic flexure",
     "Uvula away from lesion, Left RLN = aortic/lung, Wallenberg"),

    ("XI",   "Spinal Accessory", "Motor",            "Jugular foramen",
     "SCM (head turn contralateral); trapezius (shoulder shrug)",
     "Neck dissection, shoulder drop, Vernet syndrome"),

    ("XII",  "Hypoglossal",      "Motor",            "Hypoglossal canal",
     "Tongue movement (all muscles except palatoglossus)",
     "Tongue toward lesion (LMN), fasciculations = ALS, Collet-Sicard"),
]


# ─────────────────────────────────────────────────────────────
# PAGE BUILDERS
# ─────────────────────────────────────────────────────────────
W = PAGE_W - 2 * MARGIN  # usable content width


def build_cn_page(cn):
    """Build one full page of content for a single cranial nerve."""
    story = []

    # ── Nerve header box ────────────────────────────────────
    story.append(nerve_header_box(cn["num"], cn["name"], cn["emoji"], cn["fiber"]))
    story.append(Spacer(1, 8))

    # ── Origin / Exit / Target row ─────────────────────────
    oe_data = [
        [Paragraph("<b>Origin / Nuclei</b>", S["label_blue"]),
         Paragraph("<b>Skull Exit</b>",      S["label_blue"]),
         Paragraph("<b>Target Structures</b>", S["label_blue"])],
        [Paragraph(cn["origin"], S["body_small"]),
         Paragraph(cn["exit"],   S["body_small"]),
         Paragraph(cn["target"], S["body_small"])],
    ]
    oe_table = Table(oe_data, colWidths=[W*0.38, W*0.22, W*0.40])
    oe_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), LIGHT_BLUE),
        ("BACKGROUND", (0, 1), (-1, 1), WHITE),
        ("BOX",   (0, 0), (-1, -1), 0.8, DARK_BLUE),
        ("INNERGRID", (0, 0), (-1, -1), 0.4, GRAY_MID),
        ("TOPPADDING",    (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING",   (0, 0), (-1, -1), 6),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 6),
        ("VALIGN",    (0, 0), (-1, -1), "TOP"),
    ]))
    story.append(oe_table)
    story.append(Spacer(1, 8))

    # ── Pathway diagram ─────────────────────────────────────
    story.append(pathway_box(cn["pathway"], width=W))
    story.append(Spacer(1, 8))

    # ── Clinical correlations table ─────────────────────────
    clin_title_data = [[Paragraph("CLINICAL CORRELATIONS", S["section_banner"])]]
    clin_title_t = Table(clin_title_data, colWidths=[W])
    clin_title_t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), MID_BLUE),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 8),
    ]))
    story.append(clin_title_t)

    clin_rows = [[Paragraph(r[0], S["tbl_bold"]),
                  Paragraph(r[1], S["tbl_cell"])] for r in cn["clinical"]]
    clin_data = [[Paragraph("Lesion / Condition", S["tbl_hdr"]),
                  Paragraph("Key Finding / Explanation", S["tbl_hdr"])]] + clin_rows
    clin_col_w = [W * 0.35, W * 0.65]
    clin_table = Table(clin_data, colWidths=clin_col_w, repeatRows=1)
    clin_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [WHITE, ALT_ROW]),
        ("GRID", (0, 0), (-1, -1), 0.4, GRAY_MID),
        ("TOPPADDING",    (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING",   (0, 0), (-1, -1), 6),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 6),
        ("VALIGN",    (0, 0), (-1, -1), "TOP"),
    ]))
    story.append(clin_table)
    story.append(Spacer(1, 8))

    # ── High-yield keywords box ──────────────────────────────
    story.append(keyword_box(cn["keywords"], width=W))

    return story


def build_syndromes_pages():
    story = []

    # ── Section banner ──────────────────────────────────────
    story.append(section_banner("SECTION 4: CLINICAL CRANIAL NERVE SYNDROMES", color=DARK_BLUE))
    story.append(Spacer(1, 10))

    intro = ("The following syndromes result from lesions at specific anatomical locations that affect "
             "multiple cranial nerves simultaneously. Mastering these is HIGH-YIELD for all board exams.")
    story.append(Paragraph(intro, S["body"]))
    story.append(Spacer(1, 10))

    # ── Syndromes table ─────────────────────────────────────
    hdr = ["Syndrome", "Nerves\nInvolved", "Location", "Classic Cause", "Key Findings"]
    col_w = [W*0.12, W*0.12, W*0.18, W*0.24, W*0.34]

    hdr_cells = [Paragraph(h, S["tbl_hdr"]) for h in hdr]
    data = [hdr_cells]

    for i, row in enumerate(SYNDROMES):
        bg = WHITE if i % 2 == 0 else ALT_ROW
        cells = [
            Paragraph(f"<b>{row[0]}</b>", S["tbl_bold"]),
            Paragraph(row[1], S["tbl_cell_c"]),
            Paragraph(row[2], S["tbl_cell"]),
            Paragraph(row[3], S["tbl_cell"]),
            Paragraph(row[4], S["tbl_cell"]),
        ]
        data.append(cells)

    t = Table(data, colWidths=col_w, repeatRows=1)
    row_bgs = [WHITE if i % 2 == 0 else ALT_ROW for i in range(len(SYNDROMES))]
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0, 0), (-1, 0), DARK_BLUE),
        ("ROWBACKGROUNDS",(0, 1), (-1, -1), [WHITE, ALT_ROW]),
        ("GRID",  (0, 0), (-1, -1), 0.4, GRAY_MID),
        ("TOPPADDING",    (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING",   (0, 0), (-1, -1), 5),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 5),
        ("VALIGN",    (0, 0), (-1, -1), "TOP"),
        ("FONTSIZE",  (0, 0), (-1, -1), 8),
    ]))
    story.append(t)
    story.append(Spacer(1, 14))

    # ── Memory aids box ─────────────────────────────────────
    mem_lines = [
        ("<b>MEMORY AIDS FOR CN SYNDROMES</b>", S["keyword_title"]),
        ("<b>Jugular Foramen Syndromes:</b>  Vernet (IX+X+XI)  -->  Collet-Sicard (+XII)  -->  Villaret (+Horner's)", S["body_small"]),
        ("<b>Midbrain Syndromes:</b>  Weber (CN III + peduncle = hemiplegia)  |  Benedikt (CN III + red nucleus = tremor)", S["body_small"]),
        ("<b>Pontine Syndromes:</b>  Millard-Gubler (VI+VII+corticospinal)  |  Foville (VI+VII+PPRF+corticospinal)", S["body_small"]),
        ("<b>Lateral Medulla (PICA):</b>  Wallenberg — 5D rule: Dysphagia, Dysphonia, Dizziness, Diplopia, Dysmetria", S["body_small"]),
        ("<b>Frontal Lobe:</b>  Foster Kennedy — Ipsilateral anosmia + optic atrophy; Contralateral papilledema", S["body_small"]),
    ]
    cb = ColorBox(mem_lines, GREEN_LIGHT, HexColor("#2e7d32"), W, padding=8)
    story.append(cb)

    return story


def build_summary_page():
    story = []

    story.append(section_banner("SECTION 5: QUICK-REFERENCE SUMMARY — ALL 12 CRANIAL NERVES", color=DARK_BLUE))
    story.append(Spacer(1, 8))

    hdr = ["CN #", "Name", "Fiber Type", "Exit Foramen", "Key Function", "Board Keywords"]
    col_w = [W*0.05, W*0.12, W*0.11, W*0.16, W*0.22, W*0.34]

    hdr_cells = [Paragraph(h, S["tbl_hdr"]) for h in hdr]
    data = [hdr_cells]

    for row in SUMMARY_TABLE:
        cells = [
            Paragraph(f"<b>{row[0]}</b>", S["tbl_bold"]),
            Paragraph(f"<b>{row[1]}</b>", S["tbl_bold"]),
            Paragraph(row[2], S["tbl_cell_c"]),
            Paragraph(row[3], S["tbl_cell"]),
            Paragraph(row[4], S["tbl_cell"]),
            Paragraph(row[5], S["tbl_cell"]),
        ]
        data.append(cells)

    t = Table(data, colWidths=col_w, repeatRows=1)
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0, 0), (-1, 0), DARK_BLUE),
        ("ROWBACKGROUNDS",(0, 1), (-1, -1), [WHITE, ALT_ROW]),
        ("GRID",  (0, 0), (-1, -1), 0.4, GRAY_MID),
        ("TOPPADDING",    (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING",   (0, 0), (-1, -1), 4),
        ("RIGHTPADDING",  (0, 0), (-1, -1), 4),
        ("VALIGN",    (0, 0), (-1, -1), "TOP"),
        ("FONTSIZE",  (0, 0), (-1, -1), 7.5),
    ]))
    story.append(t)
    story.append(Spacer(1, 14))

    # ── Final tips box ───────────────────────────────────────
    tips = [
        ("<b>RAPID REVIEW: HIGH-YIELD BOARD FACTS</b>", S["keyword_title"]),
        ("Purely Sensory CNs: I, II, VIII  |  Purely Motor CNs: III, IV, VI, XI, XII  |  Mixed: V, VII, IX, X", S["body_small"]),
        ("CNs through Superior Orbital Fissure: III, IV, V1, VI  |  Optic canal: II + ophthalmic artery", S["body_small"]),
        ("Jugular foramen: IX, X, XI (Vernet)  |  Hypoglossal canal: XII  |  IAM: VII, VIII", S["body_small"]),
        ("Only CN exiting DORSAL brainstem: IV (Trochlear)  |  Longest intracranial course: IV (Trochlear)", S["body_small"]),
        ("Pupil constriction (miosis): CN III (Edinger-Westphal)  |  Pupil dilation: Sympathetics (T1, superior cervical ganglion)", S["body_small"]),
        ("UMN vs LMN facial palsy: UMN = forehead SPARED (bilateral cortical) | LMN = forehead INVOLVED (Bell's)", S["body_small"]),
        ("Tongue deviation: toward lesion (LMN/CN XII)  |  Uvula deviation: AWAY from lesion (CN X)", S["body_small"]),
        ("Corneal reflex: Afferent = V1  |  Efferent = VII  |  Gag reflex: Afferent = IX  |  Efferent = X", S["body_small"]),
        ("Weber test lateralizes to GOOD ear in SNHL  |  to AFFECTED ear in CHL", S["body_small"]),
    ]
    cb = ColorBox(tips, YELLOW_HL, HexColor("#c8a000"), W, padding=8)
    story.append(cb)

    return story


# ─────────────────────────────────────────────────────────────
# SECTION DIVIDER PAGE
# ─────────────────────────────────────────────────────────────
class SectionDivider(Flowable):
    """A full-page section divider with dark blue background."""
    def __init__(self, section_num, title, subtitle, cn_range):
        super().__init__()
        self.section_num = section_num
        self.title       = title
        self.subtitle    = subtitle
        self.cn_range    = cn_range

    def wrap(self, aw, ah):
        return (PAGE_W, PAGE_H)

    def draw(self):
        c = self.canv

        # Background
        c.setFillColor(DARK_BLUE)
        c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)

        # Accent rectangle
        c.setFillColor(MID_BLUE)
        c.rect(0, PAGE_H * 0.3, PAGE_W, PAGE_H * 0.4, fill=1, stroke=0)

        # Decorative circles
        c.setFillColor(HexColor("#ffffff08"))
        c.circle(PAGE_W * 0.85, PAGE_H * 0.5, 120, fill=1, stroke=0)
        c.circle(PAGE_W * 0.1,  PAGE_H * 0.8, 80,  fill=1, stroke=0)

        # Section number badge
        c.setFillColor(ACCENT_BLUE)
        c.roundRect(MARGIN, PAGE_H * 0.72, 100, 36, 6, fill=1, stroke=0)
        c.setFont("Helvetica-Bold", 14)
        c.setFillColor(WHITE)
        c.drawCentredString(MARGIN + 50, PAGE_H * 0.72 + 12, f"SECTION {self.section_num}")

        # CN range
        c.setFont("Helvetica-Bold", 48)
        c.setFillColor(WHITE)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.56, self.cn_range)

        # Title
        c.setFont("Helvetica-Bold", 22)
        c.setFillColor(LIGHT_BLUE)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.48, self.title)

        # Subtitle
        c.setFont("Helvetica", 13)
        c.setFillColor(GRAY_MID)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.43, self.subtitle)

        # Bottom bar
        c.setFillColor(HexColor("#0f2547"))
        c.rect(0, 0, PAGE_W, 40, fill=1, stroke=0)
        c.setFont("Helvetica", 9)
        c.setFillColor(ACCENT_BLUE)
        c.drawCentredString(PAGE_W / 2, 14, "FMGE  |  NEXT  |  USMLE  High-Yield Board Review")


# ─────────────────────────────────────────────────────────────
# MAIN BUILDER
# ─────────────────────────────────────────────────────────────
def build_pdf(output_path):
    doc = SimpleDocTemplate(
        output_path,
        pagesize=A4,
        leftMargin=MARGIN, rightMargin=MARGIN,
        topMargin=MARGIN + 28,   # extra top for running header
        bottomMargin=MARGIN + 20,
        title="Cranial Nerves I-XII: Complete Board Review",
        author="Medical Board Review Series",
        subject="FMGE | NEXT | USMLE High-Yield Guide",
    )

    story = []

    # ──────────── COVER PAGE ────────────────────────────────
    story.append(CoverPage())
    story.append(PageBreak())

    # ──────────── SECTION 1: CN I – IV ──────────────────────
    story.append(SectionDivider("1", "Cranial Nerves I – IV",
                                "Olfactory  |  Optic  |  Oculomotor  |  Trochlear",
                                "CN I – IV"))
    story.append(PageBreak())

    for cn in CN_DATA[:4]:
        story.extend(build_cn_page(cn))
        story.append(PageBreak())

    # ──────────── SECTION 2: CN V – VIII ────────────────────
    story.append(SectionDivider("2", "Cranial Nerves V – VIII",
                                "Trigeminal  |  Abducens  |  Facial  |  Vestibulocochlear",
                                "CN V – VIII"))
    story.append(PageBreak())

    for cn in CN_DATA[4:8]:
        story.extend(build_cn_page(cn))
        story.append(PageBreak())

    # ──────────── SECTION 3: CN IX – XII ────────────────────
    story.append(SectionDivider("3", "Cranial Nerves IX – XII",
                                "Glossopharyngeal  |  Vagus  |  Spinal Accessory  |  Hypoglossal",
                                "CN IX – XII"))
    story.append(PageBreak())

    for cn in CN_DATA[8:]:
        story.extend(build_cn_page(cn))
        story.append(PageBreak())

    # ──────────── SECTION 4: Syndromes ──────────────────────
    story.append(SectionDivider("4", "Clinical CN Syndromes",
                                "Vernet  |  Weber  |  Wallenberg  |  Benedikt  |  Millard-Gubler & more",
                                "SYNDROMES"))
    story.append(PageBreak())
    story.extend(build_syndromes_pages())
    story.append(PageBreak())

    # ──────────── SECTION 5: Summary Table ──────────────────
    story.append(SectionDivider("5", "Quick-Reference Summary Table",
                                "All 12 Cranial Nerves  |  Fiber Types  |  Foramina  |  Board Keywords",
                                "CN I – XII"))
    story.append(PageBreak())
    story.extend(build_summary_page())

    # ──────────── BUILD ──────────────────────────────────────
    doc.build(story, onFirstPage=make_page_template, onLaterPages=make_page_template)
    print(f"PDF successfully created: {output_path}")
    return output_path


# ─────────────────────────────────────────────────────────────
if __name__ == "__main__":
    out = "/home/daytona/workspace/cranial-nerves/CN_Complete_Guide.pdf"
    build_pdf(out)
Running Command

cd /home/daytona/workspace/cranial-nerves && python3 generate_cn_pdf.py 2>&1

Editing File

~/cranial-nerves/generate_cn_pdf.py

Error: String not found in file: '# ─────────────────────────────────────────────────────────────────────────────
# COVER PAGE (drawn directly on canvas for full design control)
# ─────────────────────────────────────────────────────────────────────────────
class CoverPage(Flowable):
    def __init__(self):
        super().__init__()
        self.width  = PAGE_W
        self.height = PAGE_H

    def wrap(self, aw, ah):
        return (PAGE_W, PAGE_H)

    def draw(self):
        c = self.canv

        # ── Background gradient simulation (two rects) ──
        c.setFillColor(DARK_BLUE)
        c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)

        c.setFillColor(MID_BLUE)
        c.rect(0, PAGE_H * 0.45, PAGE_W, PAGE_H * 0.55, fill=1, stroke=0)

        # ── White diagonal stripe ──
        p = c.beginPath()
        p.moveTo(0, PAGE_H * 0.44)
        p.lineTo(PAGE_W, PAGE_H * 0.48)
        p.lineTo(PAGE_W, PAGE_H * 0.44)
        p.lineTo(0, PAGE_H * 0.40)
        p.close()
        c.setFillColor(HexColor("#ffffff22"))
        c.drawPath(p, fill=1, stroke=0)

        # ── Top accent line ──
        c.setStrokeColor(ACCENT_BLUE)
        c.setLineWidth(4)
        c.line(MARGIN, PAGE_H - 12, PAGE_W - MARGIN, PAGE_H - 12)

        # ── Brain/nerve decorative circles ──
        c.setFillColor(HexColor("#ffffff08"))
        c.circle(PAGE_W * 0.82, PAGE_H * 0.72, 90, fill=1, stroke=0)
        c.circle(PAGE_W * 0.15, PAGE_H * 0.25, 60, fill=1, stroke=0)
        c.setFillColor(HexColor("#ffffff05"))
        c.circle(PAGE_W * 0.5, PAGE_H * 0.1, 130, fill=1, stroke=0)

        # ── Main Title ──
        c.setFont("Helvetica-Bold", 36)
        c.setFillColor(WHITE)
        title1 = "Cranial Nerves I\u2013XII"
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.62, title1)

        c.setFont("Helvetica-Bold", 22)
        c.setFillColor(LIGHT_BLUE)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.57, "Complete Board Review")

        # ── Horizontal rule ──
        c.setStrokeColor(ACCENT_BLUE)
        c.setLineWidth(2)
        c.line(PAGE_W * 0.2, PAGE_H * 0.545, PAGE_W * 0.8, PAGE_H * 0.545)

        # ── Subtitle / exam tags ──
        c.setFont("Helvetica-Bold", 15)
        c.setFillColor(YELLOW_HL)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.51, "FMGE  |  NEXT  |  USMLE  High-Yield Guide")

        # ── Feature bullets ──
        features = [
            "All 12 Cranial Nerves with Pathways & Clinical Correlations",
            "Major CN Syndromes: Vernet, Wallenberg, Weber, Benedikt & more",
            "Quick-Reference Summary Table  |  Board Keywords for Every Nerve",
        ]
        c.setFont("Helvetica", 11)
        c.setFillColor(LIGHT_BLUE)
        y = PAGE_H * 0.455
        for feat in features:
            c.drawCentredString(PAGE_W / 2, y, f"\u2713  {feat}")
            y -= 18

        # ── Bottom info band ──
        c.setFillColor(HexColor("#0f2547"))
        c.rect(0, 0, PAGE_W, PAGE_H * 0.12, fill=1, stroke=0)

        c.setFont("Helvetica-Bold", 11)
        c.setFillColor(ACCENT_BLUE)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.085,
                            "Anatomy  \u2022  Physiology  \u2022  Pathology  \u2022  Clinical Medicine")
        c.setFont("Helvetica", 9)
        c.setFillColor(GRAY_MID)
        c.drawCentredString(PAGE_W / 2, PAGE_H * 0.055,
                            "Comprehensive review for medical licensing examinations")

        # ── Bottom accent line ──
        c.setStrokeColor(ACCENT_BLUE)
        c.setLineWidth(3)
        c.line(MARGIN, PAGE_H * 0.13, PAGE_W - MARGIN, PAGE_H * 0.13)'
This is a shared conversation. Sign in to Orris to start your own chat.