attachment
attachment

Create a beautiful pdf on long format answers according to the numbers given to each question atleast 1 A4 sheet long Take reference from standard surgery books and also add diagrams or flowchart if any needed

analyse_media
Reading File
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Finding Sources
Reading File
Reading File
Running Command

mkdir -p /tmp/workspace/surgery-paper && ls /tmp/workspace/surgery-paper/

Writing File

~/surgery-paper/generate_pdf.py


from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.lib import colors
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, KeepTogether, PageBreak
)
from reportlab.platypus.flowables import Flowable
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.graphics.shapes import Drawing, Rect, String, Line, Arrow
from reportlab.graphics.charts.flowcharts import BasicFlowChart
from reportlab.graphics import renderPDF
import textwrap

# ─── Document setup ─────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    "/tmp/workspace/surgery-paper/MBBS_Surgery_Answers.pdf",
    pagesize=A4,
    rightMargin=2*cm, leftMargin=2*cm,
    topMargin=2*cm, bottomMargin=2*cm,
    title="MBBS Phase 3 Part 2 – Surgery Paper 1 – Model Answers",
    author="Reference: Bailey & Love, Sabiston, Robbins Pathology"
)

W, H = A4
styles = getSampleStyleSheet()

# ─── Custom styles ───────────────────────────────────────────────────────────
BLUE  = colors.HexColor("#1A3A6B")
LBLUE = colors.HexColor("#E8F0FA")
GOLD  = colors.HexColor("#B8860B")
RED   = colors.HexColor("#8B0000")
TEAL  = colors.HexColor("#006666")
LGREY = colors.HexColor("#F5F5F5")
GREEN = colors.HexColor("#1A5E3A")

def sty(name, **kw):
    s = styles[name].clone(name+"_custom_"+str(id(kw)))
    for k, v in kw.items():
        setattr(s, k, v)
    return s

cover_title = sty("Title", fontSize=20, textColor=BLUE, leading=26,
                  spaceAfter=6, alignment=TA_CENTER)
cover_sub   = sty("Normal", fontSize=13, textColor=GOLD, leading=18,
                  alignment=TA_CENTER, spaceAfter=4)
cover_note  = sty("Normal", fontSize=9, textColor=colors.grey,
                  alignment=TA_CENTER, spaceAfter=2)

q_style = sty("Heading1", fontSize=13, textColor=colors.white, leading=18,
              spaceAfter=4, spaceBefore=14)
sub_style = sty("Heading2", fontSize=11, textColor=TEAL, leading=15,
                spaceBefore=10, spaceAfter=3)
body = sty("Normal", fontSize=9.5, leading=14, spaceAfter=4,
           alignment=TA_JUSTIFY)
bullet_style = sty("Normal", fontSize=9.5, leading=13, leftIndent=14,
                   firstLineIndent=-10, spaceAfter=2, alignment=TA_JUSTIFY)
bold_body = sty("Normal", fontSize=9.5, leading=13, spaceAfter=3,
                fontName="Helvetica-Bold")
caption = sty("Normal", fontSize=8.5, textColor=colors.grey,
              alignment=TA_CENTER, spaceAfter=4)
italic_note = sty("Normal", fontSize=9, textColor=colors.grey,
                  fontName="Helvetica-Oblique", spaceAfter=3)
ref_style = sty("Normal", fontSize=8, textColor=colors.grey,
                fontName="Helvetica-Oblique", spaceAfter=2)

def B(t): return f"<b>{t}</b>"
def I(t): return f"<i>{t}</i>"
def bullet(t): return Paragraph(f"&#x2022;  {t}", bullet_style)
def numbered(n, t): return Paragraph(f"<b>{n}.</b>  {t}", bullet_style)
def sub(t): return Paragraph(t, sub_style)
def p(t): return Paragraph(t, body)
def sp(h=0.18): return Spacer(1, h*cm)

def q_header(qnum, marks, title):
    """Blue banner for question header."""
    data = [[Paragraph(f"<b>Q{qnum}. {title}</b>  <font color='#FFD700'>[{marks} Marks]</font>",
                       sty("Normal", fontSize=11, textColor=colors.white,
                           fontName="Helvetica-Bold", leading=16))]]
    t = Table(data, colWidths=[W - 4*cm])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), BLUE),
        ("TOPPADDING", (0,0), (-1,-1), 8),
        ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
        ("RIGHTPADDING", (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [4,4,4,4]),
    ]))
    return t

def sub_header(t):
    data = [[Paragraph(f"<b>{t}</b>",
                       sty("Normal", fontSize=10, textColor=TEAL,
                           fontName="Helvetica-Bold", leading=14))]]
    tbl = Table(data, colWidths=[W - 4*cm])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), LBLUE),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 8),
        ("LINEBELOW", (0,0), (-1,-1), 1, TEAL),
    ]))
    return tbl

def info_box(title, items, bg=LGREY, tc=BLUE):
    rows = [[Paragraph(f"<b>{title}</b>",
                       sty("Normal", fontSize=9.5, textColor=tc,
                           fontName="Helvetica-Bold"))]]
    for it in items:
        rows.append([bullet(it)])
    t = Table(rows, colWidths=[W - 4*cm])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("TOPPADDING", (0,0), (-1,-1), 3),
        ("BOTTOMPADDING", (0,0), (-1,-1), 3),
        ("LEFTPADDING", (0,0), (-1,-1), 8),
        ("BOX", (0,0), (-1,-1), 0.8, tc),
    ]))
    return t

def two_col_table(left_title, left_items, right_title, right_items):
    """Two-column comparison table."""
    lrows = [Paragraph(f"<b>{left_title}</b>",
                       sty("Normal", fontName="Helvetica-Bold",
                           textColor=colors.white, fontSize=9))]
    for it in left_items:
        lrows.append(Paragraph(f"• {it}", sty("Normal", fontSize=8.5, leading=12)))
    rrows = [Paragraph(f"<b>{right_title}</b>",
                       sty("Normal", fontName="Helvetica-Bold",
                           textColor=colors.white, fontSize=9))]
    for it in right_items:
        rrows.append(Paragraph(f"• {it}", sty("Normal", fontSize=8.5, leading=12)))
    max_r = max(len(lrows), len(rrows))
    while len(lrows) < max_r: lrows.append(Paragraph("", body))
    while len(rrows) < max_r: rrows.append(Paragraph("", body))
    data = [[l, r] for l, r in zip(lrows, rrows)]
    cw = (W - 4*cm - 0.3*cm) / 2
    t = Table(data, colWidths=[cw, cw])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (0,0), TEAL),
        ("BACKGROUND", (1,0), (1,0), BLUE),
        ("BACKGROUND", (0,1), (0,-1), LGREY),
        ("BACKGROUND", (1,1), (1,-1), colors.HexColor("#EEF3FF")),
        ("TOPPADDING", (0,0), (-1,-1), 3),
        ("BOTTOMPADDING", (0,0), (-1,-1), 3),
        ("LEFTPADDING", (0,0), (-1,-1), 6),
        ("BOX", (0,0), (-1,-1), 0.5, colors.grey),
        ("INNERGRID", (0,0), (-1,-1), 0.3, colors.grey),
    ]))
    return t

# ─── Flowchart drawing helper ────────────────────────────────────────────────
def flowchart_burns():
    """Simple emergency burns flowchart using Table-based boxes."""
    steps = [
        ("STEP 1", "Scene Safety + Remove patient from source", BLUE),
        ("STEP 2", "Primary Survey: Airway-Breathing-Circulation (ABC)", TEAL),
        ("STEP 3", "Assess % TBSA burn (Rule of Nines) & Depth", RED),
        ("STEP 4", "Establish IV access — 2 large bore peripheral cannulae", colors.HexColor("#4B0082")),
        ("STEP 5", "Fluid resuscitation: Parkland Formula\n4 mL × weight(kg) × %TBSA = volume in 24h\n(Half in first 8 h; rest in next 16 h)", GREEN),
        ("STEP 6", "Analgesia: IV morphine titrated + anti-emetic", colors.HexColor("#8B4513")),
        ("STEP 7", "Wound care: Cool (15-25°C water, 20 min), cover with cling film", TEAL),
        ("STEP 8", "Monitor: Urinary catheter — target 0.5 mL/kg/h adults; 1 mL/kg/h children", BLUE),
        ("STEP 9", "Nasogastric tube, Tetanus prophylaxis, Transfer if indicated", RED),
    ]
    flowable_rows = []
    for num, text, col in steps:
        row_data = [[
            Paragraph(f"<b>{num}</b>",
                      sty("Normal", fontSize=9, textColor=colors.white,
                          fontName="Helvetica-Bold", alignment=TA_CENTER)),
            Paragraph(text.replace("\n", "<br/>"),
                      sty("Normal", fontSize=9, leading=13))
        ]]
        t = Table(row_data, colWidths=[1.8*cm, W-4*cm-1.8*cm-0.4*cm])
        t.setStyle(TableStyle([
            ("BACKGROUND", (0,0), (0,-1), col),
            ("BACKGROUND", (1,0), (1,-1), LGREY),
            ("TOPPADDING", (0,0), (-1,-1), 5),
            ("BOTTOMPADDING", (0,0), (-1,-1), 5),
            ("LEFTPADDING", (0,0), (-1,-1), 6),
            ("BOX", (0,0), (-1,-1), 0.5, colors.grey),
            ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
        ]))
        flowable_rows.append(t)
        flowable_rows.append(sp(0.05))
    return flowable_rows

def rule_of_nines_table():
    data = [
        [Paragraph("<b>Body Part</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white)),
         Paragraph("<b>Adults</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white)),
         Paragraph("<b>Children (Lund-Browder)</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white))],
        ["Head & Neck", "9%", "18% at birth → decreases with age"],
        ["Each Upper Limb", "9%", "9%"],
        ["Anterior Trunk", "18%", "18%"],
        ["Posterior Trunk", "18%", "18%"],
        ["Each Lower Limb", "18%", "14% at birth → increases with age"],
        ["Genitalia/Perineum", "1%", "1%"],
    ]
    cw = (W-4*cm)/3
    t = Table(data, colWidths=[cw, cw, cw])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), BLUE),
        ("TEXTCOLOR", (0,0), (-1,0), colors.white),
        ("BACKGROUND", (0,1), (-1,-1), LGREY),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [LGREY, colors.white]),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 6),
        ("BOX", (0,0), (-1,-1), 0.8, BLUE),
        ("INNERGRID", (0,0), (-1,-1), 0.3, colors.grey),
        ("FONTNAME", (0,1), (-1,-1), "Helvetica"),
        ("FONTSIZE", (0,1), (-1,-1), 9),
    ]))
    return t

def thyroiditis_table():
    data = [
        [Paragraph("<b>Type</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white)),
         Paragraph("<b>Features</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white)),
         Paragraph("<b>Management</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white))],
        ["Hashimoto's\n(Chronic lymphocytic)",
         "Autoimmune; Anti-TPO & anti-TG Ab +ve; hypothyroidism; Hurthle cell change; germinal centres",
         "Levothyroxine replacement; monitor TSH"],
        ["De Quervain's\n(Subacute granulomatous)",
         "Viral etiology; painful tender goitre; fever; ESR ↑; RAIU ↓; transient thyrotoxicosis",
         "NSAIDs/Aspirin; Prednisolone 40mg/d for severe; β-blockers if symptomatic thyrotoxicosis"],
        ["Painless/Silent\n(Subacute lymphocytic)",
         "Autoimmune; postpartum variant; no pain; transient thyrotoxicosis then hypothyroidism",
         "Observation; β-blockers if needed; levothyroxine if hypothyroid persists"],
        ["Riedel's\n(Fibrous thyroiditis)",
         "Dense fibrosis; 'iron hard' goitre; may cause tracheal compression; rare",
         "Surgery if compressive; tamoxifen reported helpful"],
        ["Acute Suppurative",
         "Bacterial (Staph/Strep); tender, hot, red; fever; abscess formation; rare",
         "Antibiotics; surgical drainage if abscess"],
        ["Radiation-induced",
         "After 131I therapy; transient thyroiditis; usually mild",
         "Symptomatic; anti-inflammatory"],
    ]
    cw_vals = [3.2*cm, (W-4*cm-3.2*cm-4.5*cm), 4.5*cm]
    t = Table(data, colWidths=cw_vals, repeatRows=1)
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), BLUE),
        ("TEXTCOLOR", (0,0), (-1,0), colors.white),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [LGREY, colors.white]),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("BOX", (0,0), (-1,-1), 0.8, BLUE),
        ("INNERGRID", (0,0), (-1,-1), 0.3, colors.grey),
        ("FONTNAME", (0,1), (-1,-1), "Helvetica"),
        ("FONTSIZE", (0,1), (-1,-1), 8.5),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("WORDWRAP", (0,0), (-1,-1), True),
    ]))
    return t

def keloid_vs_hypertrophic():
    data = [
        [Paragraph("<b>Feature</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white)),
         Paragraph("<b>Keloid</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white)),
         Paragraph("<b>Hypertrophic Scar</b>", sty("Normal", fontSize=9, fontName="Helvetica-Bold", textColor=colors.white))],
        ["Extension beyond wound", "Yes (clawlike projections)", "No"],
        ["Spontaneous regression", "No", "Yes (months)"],
        ["Histology", "Thick hyalinised collagen bundles", "Whorled fibroblasts without hyalinisation"],
        ["Incidence", "More in dark skin", "Any skin type"],
        ["Recurrence after excision", "High", "Low"],
        ["Pruritus/Pain", "Common", "Less common"],
    ]
    cw = (W-4*cm)/3
    t = Table(data, colWidths=[cw, cw, cw])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), RED),
        ("TEXTCOLOR", (0,0), (-1,0), colors.white),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [LGREY, colors.white]),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 6),
        ("BOX", (0,0), (-1,-1), 0.8, RED),
        ("INNERGRID", (0,0), (-1,-1), 0.3, colors.grey),
        ("FONTNAME", (0,1), (-1,-1), "Helvetica"),
        ("FONTSIZE", (0,1), (-1,-1), 9),
    ]))
    return t

# ═══════════════════════════════════════════════════════════════════════════════
# BUILD CONTENT
# ═══════════════════════════════════════════════════════════════════════════════
story = []

# ─── COVER ───────────────────────────────────────────────────────────────────
story.append(sp(3))
story.append(Paragraph("MBBS PHASE 3 PART 2 — PAPER 1", cover_title))
story.append(Paragraph("Surgery — Model Long Answers", cover_sub))
story.append(sp(0.3))
story.append(HRFlowable(width="100%", thickness=2, color=GOLD, spaceAfter=6))
story.append(Paragraph(
    "Reference Sources: Bailey &amp; Love's Short Practice of Surgery (28th ed.) • "
    "Sabiston Textbook of Surgery (21st ed.) • Schwartz's Principles of Surgery (11th ed.) • "
    "Robbins &amp; Kumar Basic Pathology • Cummings Otolaryngology • Andrews' Diseases of the Skin",
    cover_note))
story.append(HRFlowable(width="100%", thickness=1, color=GOLD, spaceAfter=8))
story.append(sp(1))

# ─── TABLE OF CONTENTS ───────────────────────────────────────────────────────
toc_data = [
    [Paragraph("<b>Question</b>", sty("Normal", fontSize=10, fontName="Helvetica-Bold", textColor=colors.white)),
     Paragraph("<b>Topic</b>", sty("Normal", fontSize=10, fontName="Helvetica-Bold", textColor=colors.white)),
     Paragraph("<b>Marks</b>", sty("Normal", fontSize=10, fontName="Helvetica-Bold", textColor=colors.white))],
    ["Q2", "Surgical Anatomy of Thyroid + Types of Thyroiditis & Management", "20"],
    ["Q3a", "Lipoma and its Types", "5"],
    ["Q3b", "Neurofibroma", "5"],
    ["Q3c", "Total Parenteral Nutrition (TPN)", "5"],
    ["Q3d", "Compartment Syndrome", "5"],
    ["Q3e", "Keloid", "5"],
    ["Q4a", "Why Malignancy is Less Common in Small Intestine", "5"],
    ["Q4b", "Why Appendicitis Must Be Managed Earlier in Children & Elderly", "5"],
    ["Q5a", "Lupus Vulgaris", "5"],
    ["Q5b", "Tropical Ulcer", "5"],
    ["Q5c", "Fistula", "5"],
    ["Q5d", "Hidradenitis Suppurativa", "5"],
    ["Q5e", "Zollinger–Ellison Syndrome", "5"],
    ["Q6", "Emergency Management of Burns Victim", "10"],
]
toc_cw = [1.5*cm, W-4*cm-1.5*cm-1.5*cm, 1.5*cm]
toc_t = Table(toc_data, colWidths=toc_cw)
toc_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), BLUE),
    ("TEXTCOLOR", (0,0), (-1,0), colors.white),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LGREY, colors.white]),
    ("TOPPADDING", (0,0), (-1,-1), 4),
    ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("BOX", (0,0), (-1,-1), 0.8, BLUE),
    ("INNERGRID", (0,0), (-1,-1), 0.3, colors.grey),
    ("FONTSIZE", (0,1), (-1,-1), 9),
    ("ALIGN", (2,0), (2,-1), "CENTER"),
]))
story.append(Paragraph("Contents", sty("Heading1", textColor=BLUE)))
story.append(toc_t)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# Q2 — Thyroid Surgical Anatomy + Thyroiditis (20 marks)
# ══════════════════════════════════════════════════════════════════════════════
story.append(q_header(2, 20,
    "Surgical Anatomy of Thyroid. Types of Thyroiditis and their Management."))
story.append(sp())

story.append(sub_header("PART A: SURGICAL ANATOMY OF THE THYROID GLAND"))
story.append(sp(0.1))

story.append(p(
    "<b>Position and Shape:</b> The thyroid gland is a bilobed, H-shaped endocrine gland located in the "
    "anterior neck, deep to the strap muscles (sternohyoid, sternothyroid, and omohyoid). "
    "It lies at the level of C5–T1 vertebrae and straddles the trachea and larynx. "
    "The two lateral lobes are joined by the isthmus which overlies the 2nd–4th tracheal rings. "
    "A pyramidal lobe ascends from the isthmus in ~50% of individuals, representing a remnant of the "
    "thyroglossal duct."
))
story.append(p(
    "<b>Dimensions and Weight:</b> Each lobe is approximately 5 cm long, 3 cm wide, and 2 cm thick. "
    "The normal gland weighs 25–40 g. The isthmus is ~2 cm wide and 2 cm tall."
))

story.append(sub("1. Capsule and Fascial Relationships"))
story.append(p(
    "The thyroid is enclosed by a true fibrous capsule which sends septa into the parenchyma. "
    "External to this is the pretracheal fascia (false capsule/surgical capsule), a condensation "
    "of which forms <b>Berry's ligament</b> — a dense band binding the posteromedial lobe to "
    "the trachea and cricoid cartilage. This ligament is surgically important as it is the point "
    "of greatest risk to the <b>recurrent laryngeal nerve (RLN)</b>. The subcapsular plane "
    "(between true and false capsule) is the correct surgical dissection plane."
))

story.append(sub("2. Blood Supply"))
story.append(p("<b>Arterial supply (4 arteries):</b>"))
story.append(bullet("<b>Superior thyroid artery</b> — first branch of the external carotid artery; "
                    "enters the upper pole of each lobe; accompanied by the external branch of the "
                    "superior laryngeal nerve (EBSLN) which must be identified and preserved."))
story.append(bullet("<b>Inferior thyroid artery</b> — from the thyrocervical trunk (subclavian artery); "
                    "enters the lower pole; intimately related to the RLN. "
                    "The relationship is variable: nerve may pass anterior or posterior to the artery."))
story.append(bullet("<b>Thyroidea ima artery</b> — inconstant; arises from the aorta or innominate artery; "
                    "enters the isthmus inferiorly (present in ~3% of individuals)."))
story.append(sp(0.1))
story.append(p("<b>Venous drainage (3 veins per side):</b>"))
story.append(bullet("<b>Superior thyroid vein</b> → drains to internal jugular vein"))
story.append(bullet("<b>Middle thyroid vein</b> → drains to internal jugular vein (no accompanying artery; "
                    "first structure ligated during thyroidectomy)"))
story.append(bullet("<b>Inferior thyroid veins</b> → drain into left brachiocephalic vein (may be bilateral)"))

story.append(sub("3. Nerve Relations — Critical for Surgery"))
story.append(p("<b>Recurrent Laryngeal Nerve (RLN):</b>"))
story.append(bullet("Branch of vagus nerve"))
story.append(bullet("Right RLN loops under the subclavian artery; Left loops under the aortic arch "
                    "(longer course, more susceptible to injury in mediastinal pathology)"))
story.append(bullet("Runs in the tracheo-oesophageal groove then passes deep to Berry's ligament"))
story.append(bullet("Found at the <b>Tubercle of Zuckerkandl</b> — a posterolateral projection "
                    "of the thyroid lobe; the RLN lies medial to it"))
story.append(bullet("Injury causes hoarseness (unilateral) or respiratory distress (bilateral)"))
story.append(sp(0.1))
story.append(p("<b>External Branch of the Superior Laryngeal Nerve (EBSLN):</b>"))
story.append(bullet("Runs adjacent to the superior thyroid pedicle; innervates the cricothyroid muscle"))
story.append(bullet("Injury causes loss of high-pitched phonation ('voice of the surgeon's nightmare')"))

story.append(sub("4. Parathyroid Glands"))
story.append(p(
    "Four parathyroid glands (superior and inferior pairs) lie adjacent to or within the posterior "
    "capsule of the thyroid. <b>Superior parathyroids</b> are more constant (at the level of the "
    "cricothyroid junction). <b>Inferior parathyroids</b> are more variable — may be as low as "
    "the mediastinum. Blood supply is via the inferior thyroid artery. "
    "Careful preservation is essential to avoid post-operative hypocalcaemia."
))

story.append(sub("5. Lymphatic Drainage"))
story.append(p(
    "Lymphatics drain to: <b>prelaryngeal</b> (Delphian node), <b>pretracheal</b>, "
    "<b>paratracheal</b>, and <b>deep cervical</b> nodes. "
    "Lateral spread to jugulodigastric and posterior triangle nodes also occurs. "
    "This pathway is relevant in thyroid cancer staging and node dissection."
))

story.append(sub("6. Embryology (Surgical Relevance)"))
story.append(bullet("Develops from the floor of the pharynx at the foramen caecum (base of tongue) "
                    "at 24 days"))
story.append(bullet("Descends via the thyroglossal duct to its final position"))
story.append(bullet("Incomplete descent → lingual thyroid (most common ectopic site); "
                    "incomplete obliteration → thyroglossal cyst"))
story.append(bullet("C cells originate from neural crest via the ultimobranchial bodies"))

story.append(sp(0.3))
story.append(sub_header("PART B: TYPES OF THYROIDITIS AND MANAGEMENT"))
story.append(sp(0.1))
story.append(p(
    "Thyroiditis refers to inflammation of the thyroid gland. The common feature is disruption of "
    "thyroid follicles → release of preformed T3/T4 → <b>transient thyrotoxicosis</b>, followed "
    "potentially by <b>transient hypothyroidism</b> as stores are depleted. "
    "Permanent hypothyroidism occurs in Hashimoto's thyroiditis."
))
story.append(sp(0.1))
story.append(thyroiditis_table())
story.append(sp(0.1))
story.append(p(
    I("References: Bailey &amp; Love 28th ed., Chapter 55; Robbins &amp; Kumar Basic Pathology; "
      "Cummings Otolaryngology Head and Neck Surgery")
))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# Q3 — SHORT NOTES (25 marks)
# ══════════════════════════════════════════════════════════════════════════════
story.append(q_header(3, 25,
    "Short Notes (5 marks each): Lipoma | Neurofibroma | TPN | Compartment Syndrome | Keloid"))
story.append(sp())

# Q3a — Lipoma
story.append(sub_header("Q3a) LIPOMA AND ITS TYPES"))
story.append(p(
    "<b>Definition:</b> A lipoma is the most common soft tissue tumour, composed of mature "
    "adipocytes. It is benign, slow-growing, and encapsulated. Occurs in any fatty tissue."
))
story.append(p("<b>Macroscopy:</b> Soft, lobulated, yellowish mass; slips between examining fingers "
               "(slip sign). Encapsulated with thin fibrous capsule."))
story.append(p("<b>Microscopy:</b> Mature adipocytes indistinguishable from normal fat, arranged in lobules "
               "separated by fibrous septa."))
story.append(sub("Types of Lipoma"))
story.append(bullet("<b>Simple/Superficial Lipoma:</b> Most common; subcutaneous, soft, fluctuant "
                    "(pseudofluctuance), transilluminable, non-tender, mobile"))
story.append(bullet("<b>Deep lipoma:</b> Subfascial, submuscular, subsynovial — harder to diagnose "
                    "clinically; requires MRI"))
story.append(bullet("<b>Angiolipoma:</b> Contains blood vessels; tender; usually forearm; "
                    "multiple and painful"))
story.append(bullet("<b>Fibrolipoma:</b> Abundant fibrous tissue; firmer consistency"))
story.append(bullet("<b>Myxolipoma:</b> Contains mucoid degeneration areas"))
story.append(bullet("<b>Myelolipoma:</b> Contains haematopoietic tissue; found in adrenal gland"))
story.append(bullet("<b>Hibernoma:</b> Brown fat tumour; interscapular region; more vascular"))
story.append(bullet("<b>Pleomorphic lipoma/Spindle cell lipoma:</b> Seen in elderly men; "
                    "back/shoulder; contains atypical giant cells — benign"))
story.append(bullet("<b>Diffuse lipomatosis:</b> Unencapsulated fat proliferation in a body region "
                    "(Madelung's disease — symmetric cervical lipomatosis)"))
story.append(bullet("<b>Lipoma arborescens:</b> Villous frond-like synovial lipoma; usually knee"))
story.append(p(
    "<b>Malignant counterpart:</b> Liposarcoma. Suspect if: rapidly enlarging, size >5 cm, "
    "deep to fascia, hard/fixed. Biopsy mandatory before excision."
))
story.append(p("<b>Treatment:</b> Surgical excision with intact capsule through appropriate incision. "
               "Liposuction for cosmesis in selected cases."))
story.append(sp())

# Q3b — Neurofibroma
story.append(sub_header("Q3b) NEUROFIBROMA"))
story.append(p(
    "<b>Definition:</b> A benign peripheral nerve sheath tumour arising from Schwann cells, "
    "fibroblasts, and perineural cells of peripheral nerves. May occur sporadically or in association "
    "with <b>Neurofibromatosis type 1 (NF-1, von Recklinghausen's disease)</b>."
))
story.append(p("<b>Pathology:</b> Unencapsulated tumour with spindle-shaped cells embedded in "
               "myxoid stroma with collagen. S-100 protein positive on immunohistochemistry."))
story.append(sub("Types"))
story.append(bullet("<b>Localized (cutaneous) neurofibroma:</b> Most common; solitary; "
                    "soft, flesh-coloured skin nodule; buttonhole sign (invaginates on pressure)"))
story.append(bullet("<b>Plexiform neurofibroma:</b> Multiple nerve fascicles involved; "
                    "produces 'bag of worms' feel; <b>pathognomonic of NF-1</b>; "
                    "higher risk of malignant transformation"))
story.append(bullet("<b>Diffuse neurofibroma:</b> Infiltrates dermis and subcutis; "
                    "plaquelike thickening; usually head/neck in young patients"))
story.append(sub("Neurofibromatosis Type 1 (NF-1)"))
story.append(p(
    "Autosomal dominant; chromosome 17q11.2 mutation; NF1 gene encodes neurofibromin (tumour suppressor). "
    "Diagnosis: <b>2 or more</b> of the following (NIH criteria):"
))
story.append(bullet("≥6 café-au-lait macules (>5 mm prepubertal; >15 mm postpubertal)"))
story.append(bullet("≥2 neurofibromas or ≥1 plexiform neurofibroma"))
story.append(bullet("Axillary/inguinal freckling (Crowe's sign)"))
story.append(bullet("Optic glioma"))
story.append(bullet("≥2 Lisch nodules (iris hamartomas)"))
story.append(bullet("Distinctive osseous lesion (sphenoid wing dysplasia)"))
story.append(bullet("First-degree relative with NF-1"))
story.append(p(
    "<b>Complications:</b> Malignant peripheral nerve sheath tumour (MPNST) in 2–5%; "
    "scoliosis, learning disability, hypertension (from renovascular disease or "
    "phaeochromocytoma), epilepsy."
))
story.append(p("<b>Treatment:</b> Surgical excision for symptomatic or suspicious lesions. "
               "Selumetinib (MEK inhibitor) approved for inoperable plexiform neurofibromas in NF-1."))
story.append(sp())

# Q3c — TPN
story.append(sub_header("Q3c) TOTAL PARENTERAL NUTRITION (TPN)"))
story.append(p(
    "<b>Definition:</b> Provision of all nutritional requirements (calories, protein, fat, "
    "electrolytes, vitamins, trace elements, water) via the intravenous route, bypassing the GI tract."
))
story.append(p("<b>Indications (when gut cannot be used):</b>"))
story.append(bullet("Short bowel syndrome"))
story.append(bullet("High-output intestinal fistulae"))
story.append(bullet("Prolonged ileus / intestinal obstruction"))
story.append(bullet("Severe pancreatitis with enteral feeding intolerance"))
story.append(bullet("Inflammatory bowel disease (severe Crohn's with failure to thrive)"))
story.append(bullet("Post-major GI surgery when enteral feeding not possible >5–7 days"))
story.append(bullet("Mesenteric ischaemia; intestinal pseudo-obstruction"))
story.append(sub("Components of TPN Solution"))
story.append(bullet("<b>Carbohydrate:</b> Glucose (50–60% of non-protein calories); 3.4 kcal/g; "
                    "max 4–5 mg/kg/min to avoid hyperglycaemia"))
story.append(bullet("<b>Lipid emulsion:</b> 20–40% of total calories; "
                    "soya/olive/fish oil-based; provides essential fatty acids"))
story.append(bullet("<b>Amino acids:</b> 1–1.5 g/kg/day; provides nitrogen for protein synthesis"))
story.append(bullet("<b>Electrolytes:</b> Na+, K+, Mg2+, Ca2+, PO4 3− — tailored daily"))
story.append(bullet("<b>Vitamins:</b> Fat-soluble (A, D, E, K) and water-soluble (B-complex, C)"))
story.append(bullet("<b>Trace elements:</b> Zn, Cu, Mn, Se, Cr, Mo"))
story.append(bullet("<b>Water:</b> ~30–35 mL/kg/day"))
story.append(sub("Monitoring"))
story.append(bullet("Daily: Blood glucose, U&amp;E, fluid balance, line site"))
story.append(bullet("Twice weekly: LFTs, magnesium, phosphate"))
story.append(bullet("Weekly: Triglycerides, trace elements, vitamin levels"))
story.append(sub("Complications"))
story.append(p("<b>Line-related:</b> Pneumothorax, arterial injury, air embolism, line sepsis "
               "(Staphylococcus epidermidis most common), thrombosis"))
story.append(p("<b>Metabolic:</b>"))
story.append(bullet("Hyperglycaemia → insulin therapy required"))
story.append(bullet("Refeeding syndrome → hypophosphataemia, hypokalaemia, hypomagnesaemia "
                    "(risk if malnourished patient refed rapidly)"))
story.append(bullet("Hepatic steatosis/IFALD (Intestinal Failure Associated Liver Disease)"))
story.append(bullet("Essential fatty acid deficiency if fat-free TPN prolonged"))
story.append(p("<b>Route:</b> Central venous access mandatory (high osmolarity ~1800 mOsm/L). "
               "Common sites: subclavian, internal jugular, PICC line."))
story.append(sp())

# Q3d — Compartment Syndrome
story.append(sub_header("Q3d) COMPARTMENT SYNDROME"))
story.append(p(
    "<b>Definition:</b> A condition in which increased pressure within a closed fascial compartment "
    "compromises tissue perfusion, leading to ischaemia and necrosis if untreated. "
    "Defined as compartment pressure >30 mmHg OR within 30 mmHg of diastolic blood pressure "
    "(delta P = diastolic BP - compartment pressure &lt;30 mmHg)."
))
story.append(sub("Aetiology / Causes"))
story.append(bullet("<b>Fractures:</b> Tibial shaft fracture (most common), forearm fractures"))
story.append(bullet("Crush injuries, high energy trauma"))
story.append(bullet("Reperfusion after vascular injury/ischaemia"))
story.append(bullet("Burns — circumferential full-thickness burns"))
story.append(bullet("Constrictive casts, tight wound dressings"))
story.append(bullet("Bleeding diathesis, anticoagulation"))
story.append(bullet("Snakebite envenomation, IV drug use extravasation"))
story.append(sub("Pathophysiology"))
story.append(p(
    "Raised compartment pressure → venous outflow obstruction → further oedema → "
    "pressure exceeds capillary perfusion pressure → arterial inflow diminished → "
    "ischaemia → cell necrosis → rhabdomyolysis → myoglobinuria → renal failure."
))
story.append(sub("Clinical Features — 6 Ps"))
for itm in ["<b>Pain</b> — disproportionate to injury; pain on passive stretch (earliest and most reliable sign)",
            "<b>Pressure</b> — tense, woody compartment on palpation",
            "<b>Paraesthesia</b> — tingling/numbness in distribution of nerve within compartment",
            "<b>Paralysis</b> — weakness/inability to move affected muscles (late sign)",
            "<b>Pallor</b> — pale skin",
            "<b>Pulselessness</b> — very late sign; presence of pulse does NOT exclude compartment syndrome"]:
    story.append(bullet(itm))
story.append(sub("Diagnosis"))
story.append(bullet("Clinical diagnosis primarily"))
story.append(bullet("Compartment pressure measurement: Stryker device or modified arterial line"))
story.append(bullet("Delta P = Diastolic BP − Compartment Pressure; if &lt;30 mmHg → fasciotomy"))
story.append(sub("Management"))
story.append(p("<b>Emergency fasciotomy</b> — definitive treatment; must not be delayed."))
story.append(bullet("Lower leg: 2-incision 4-compartment fasciotomy (medial + lateral incisions)"))
story.append(bullet("Forearm: Volar + dorsal fasciotomy"))
story.append(bullet("Thigh: Single lateral incision"))
story.append(bullet("Hand/foot: Multiple dorsal incisions"))
story.append(p("Post-fasciotomy: wound left open, dressed with negative pressure wound therapy "
               "(NPWT) or wet dressings; closed at 48–72 hours or split-skin grafting as needed."))
story.append(p("<b>Secondary management:</b> Monitor renal function (myoglobinuria); "
               "IV fluids to maintain urine output >1 mL/kg/h; alkalinise urine if needed; "
               "monitor electrolytes (hyperkalaemia from cell lysis)."))
story.append(sp())

# Q3e — Keloid
story.append(sub_header("Q3e) KELOID"))
story.append(p(
    "<b>Definition:</b> A keloid is an exuberant, firm, fibrous scar that extends beyond the margins "
    "of the original wound (distinguishing it from a hypertrophic scar). "
    "It represents a pathological response to wound healing with excessive deposition of collagen."
))
story.append(p(
    "<b>Epidemiology:</b> More common in dark-skinned individuals (African, Asian populations); "
    "15–20 times more common in black persons. Peak incidence: 10–30 years."
))
story.append(sub("Aetiology"))
story.append(bullet("Trauma: incisions, lacerations, burns, acne, ear piercing, tattooing, vaccinations"))
story.append(bullet("Genetic predisposition: higher concordance in monozygotic twins"))
story.append(bullet("Sites of predilection: sternum, shoulders, upper back, earlobes, neck"))
story.append(sub("Pathology"))
story.append(p(
    "Microscopically: <b>thick, hyalinised collagen bundles</b> (distinguishing feature from "
    "hypertrophic scar) arranged in whorls; myofibroblasts; increased mucopolysaccharides; "
    "numerous mast cells. Epidermis thinned due to pressure."
))
story.append(keloid_vs_hypertrophic())
story.append(sp(0.1))
story.append(sub("Treatment"))
story.append(bullet("<b>Intralesional corticosteroid injection</b> (triamcinolone 10–40 mg/mL): "
                    "first-line; injections every 6–8 weeks; causes softening and itch relief"))
story.append(bullet("<b>Pressure therapy:</b> Silicone gel sheets, pressure garments — "
                    "worn 23 h/day for ≥6 months; most effective for burn keloids"))
story.append(bullet("<b>Surgical excision:</b> High recurrence (up to 80%) if used alone; "
                    "must be combined with adjuvant therapy"))
story.append(bullet("<b>Radiotherapy:</b> Post-excision superficial radiotherapy reduces recurrence; "
                    "avoid in children"))
story.append(bullet("<b>Laser therapy:</b> Pulsed dye laser (595 nm) reduces vascularity and redness"))
story.append(bullet("<b>Intralesional 5-FU/bleomycin:</b> Used in combination with steroids "
                    "for resistant keloids"))
story.append(bullet("<b>Cryotherapy:</b> Useful for small lesions"))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# Q4 — EXPLAIN WHY (10 marks)
# ══════════════════════════════════════════════════════════════════════════════
story.append(q_header(4, 10,
    "Explain Why: a) Malignancy Rare in Small Intestine  b) Appendicitis: Earlier Management"))
story.append(sp())

story.append(sub_header("Q4a) WHY IS MALIGNANCY LESS COMMON IN THE SMALL INTESTINE?"))
story.append(p(
    "Despite accounting for 75% of the length and 90% of the mucosal surface area of the "
    "alimentary tract, the small intestine accounts for only <b>1–3% of all GI malignancies</b>. "
    "This paradox is explained by several protective mechanisms:"
))
story.append(p("<b>1. Rapid Transit Time:</b>"))
story.append(p(
    "Small intestinal contents are in liquid form and transit is rapid (2–6 hours), "
    "minimising contact time of potential carcinogens (bile acids, food-derived mutagens) "
    "with the mucosa. In contrast, colonic transit takes 24–72 hours."
))
story.append(p("<b>2. Liquid Luminal Content:</b>"))
story.append(p(
    "The liquid consistency reduces mechanical mucosal trauma and abrasion compared to "
    "the formed stool in the colon. This minimises DNA damage from physical irritation."
))
story.append(p("<b>3. High Immunological Activity (Gut-Associated Lymphoid Tissue — GALT):</b>"))
story.append(p(
    "Peyer's patches in the ileum contain abundant lymphoid tissue with macrophages, "
    "IgA-secreting plasma cells, and T-lymphocytes. High IgA concentrations neutralise "
    "carcinogens and antigens before mucosal contact. This immunosurveillance rapidly "
    "eliminates transformed cells."
))
story.append(p("<b>4. Alkaline pH:</b>"))
story.append(p(
    "The small intestinal pH is alkaline (6.5–7.5) compared to the acidic faecal content "
    "of the colon. Bile acids are less cytotoxic and carcinogenic at alkaline pH. "
    "Secondary bile acids (deoxycholate, lithocholate — known carcinogens) are formed "
    "by bacterial action, which is minimal in the small bowel."
))
story.append(p("<b>5. Low Bacterial Count:</b>"))
story.append(p(
    "The small bowel has a relatively sparse bacterial flora (10^3–10^4 organisms/mL) "
    "due to rapid transit and high IgA. The colon has 10^11 organisms/mL. "
    "Bacteria in the colon generate carcinogenic metabolites from bile acids and "
    "dietary substances (heterocyclic amines, N-nitroso compounds)."
))
story.append(p("<b>6. Rapid Epithelial Turnover:</b>"))
story.append(p(
    "Small intestinal enterocytes have a very high turnover rate (3–5 days), "
    "meaning any cell accumulating mutations is rapidly shed before transformation. "
    "Apoptotic mechanisms are highly active."
))
story.append(p("<b>7. High Local Levels of Benzpyrene Hydroxylase:</b>"))
story.append(p(
    "This enzyme detoxifies polycyclic aromatic hydrocarbons (a class of carcinogens) "
    "within the small bowel mucosa."
))
story.append(p(
    "<b>Conclusion:</b> The combination of rapid transit, alkaline milieu, low bacterial load, "
    "robust immunological surveillance, high epithelial turnover, and detoxifying enzymes "
    "collectively make the small intestine remarkably resistant to carcinogenesis."
))
story.append(sp())

story.append(sub_header("Q4b) WHY MUST APPENDICITIS BE MANAGED EARLIER IN CHILDREN AND ELDERLY?"))
story.append(p(
    "Acute appendicitis can progress to perforation, peritonitis, and sepsis rapidly. "
    "However, in the <b>paediatric</b> and <b>elderly</b> populations, this progression "
    "is accelerated and the consequences are more severe, necessitating earlier intervention:"
))
story.append(sub("In CHILDREN (especially under 5 years)"))
story.append(p("<b>1. Underdeveloped/thin-walled appendix:</b> The appendix wall is thinner "
               "and less able to withstand pressure — perforation occurs within 24–36 hours "
               "of symptom onset (vs. 48–72 hours in adults)."))
story.append(p("<b>2. Immature omentum:</b> The greater omentum is small and underdeveloped "
               "in young children and cannot 'wall off' or localise a perforated appendix. "
               "This leads to <b>generalised peritonitis</b> rather than a localised appendix abscess."))
story.append(p("<b>3. Poor history and diagnostic difficulty:</b> Young children cannot localise "
               "pain accurately. Clinical features are often atypical (diffuse abdominal pain, "
               "vomiting, diarrhoea), causing diagnostic delay and late presentation."))
story.append(p("<b>4. Rapid dehydration and sepsis:</b> Children have higher surface area to "
               "volume ratio; fluid losses and electrolyte imbalance occur faster; septic shock "
               "can develop quickly."))
story.append(p("<b>5. Rapidly progressing inflammatory response:</b> Higher metabolic rate "
               "accelerates the inflammatory cascade."))
story.append(sub("In ELDERLY (over 60 years)"))
story.append(p("<b>1. Impaired immune response:</b> Immunosenescence means the inflammatory "
               "response is blunted; classical signs (fever, leukocytosis, rebound tenderness) "
               "may be absent or minimal, causing late diagnosis."))
story.append(p("<b>2. Atypical presentation:</b> Pain may be mild or diffuse; temperature may "
               "be normal or mildly elevated; leukocytosis may be absent (20% of elderly "
               "perforations have normal WBC)."))
story.append(p("<b>3. Higher perforation rate:</b> 70% of elderly patients present with perforated "
               "appendicitis (vs. 20–30% in younger adults) due to diagnostic delay."))
story.append(p("<b>4. Co-morbidities:</b> Hypertension, diabetes, COPD, cardiac disease, "
               "anticoagulant use — all increase surgical risk and complications. "
               "Early surgery when patient is better physiologically conditioned is safer."))
story.append(p("<b>5. Thickened, fibrotic appendiceal wall:</b> Paradoxically, although the "
               "wall is thicker (from previous inflammation), blood supply may be atheromatous "
               "and reduced, predisposing to earlier ischaemic perforation."))
story.append(p("<b>6. Higher mortality from perforation:</b> Mortality from perforated appendicitis "
               "is up to 15% in the elderly vs. &lt;1% in young adults. Earlier appendicectomy "
               "prevents this fatal complication."))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# Q5 — SHORT NOTES (25 marks)
# ══════════════════════════════════════════════════════════════════════════════
story.append(q_header(5, 25,
    "Short Notes: Lupus Vulgaris | Tropical Ulcer | Fistula | Hidradenitis Suppurativa | Zollinger–Ellison"))
story.append(sp())

# Q5a — Lupus Vulgaris
story.append(sub_header("Q5a) LUPUS VULGARIS"))
story.append(p(
    "<b>Definition:</b> Lupus vulgaris is the most common and severe form of cutaneous tuberculosis, "
    "caused by <i>Mycobacterium tuberculosis</i>. It is a chronic, progressive, destructive form of "
    "skin TB that can lead to permanent disfigurement."
))
story.append(p(
    "<b>Pathogenesis:</b> Usually represents reactivation or haematogenous/lymphatic seeding "
    "in a previously sensitised individual. Also may arise from direct inoculation or contiguous spread. "
    "Tuberculin test strongly positive (high sensitisation)."
))
story.append(sub("Clinical Features"))
story.append(bullet("Sites: Head and neck (commonest — especially nose and cheek), "
                    "buttocks, extremities"))
story.append(bullet("Primary lesion: Apple-jelly nodule (lupoma) — reddish-brown, "
                    "translucent papule/nodule showing characteristic <b>apple-jelly colour</b> "
                    "on diascopy (glass slide pressure)"))
story.append(bullet("Lesions coalesce into plaques with irregular borders; central scarring "
                    "with active advancing edge"))
story.append(bullet("Ulceration and crusting in long-standing cases"))
story.append(bullet("Mutilating destruction of nose (lupus nasi), ears, lips"))
story.append(bullet("Squamous cell carcinoma can develop in longstanding lupus vulgaris scars (Marjolin's ulcer)"))
story.append(sub("Investigations"))
story.append(bullet("Skin biopsy: Epithelioid cell granulomas with Langhans giant cells; "
                    "central caseation uncommon"))
story.append(bullet("AFB smear/culture from lesion"))
story.append(bullet("Tuberculin test (Mantoux) — strongly positive"))
story.append(bullet("Chest X-ray (active/previous TB)"))
story.append(bullet("QuantiFERON-TB Gold or ELISPOT"))
story.append(sub("Management"))
story.append(p("<b>Anti-tuberculosis therapy</b> as per standard 6-month regimen:"))
story.append(bullet("Intensive phase (2 months): Isoniazid + Rifampicin + Pyrazinamide + Ethambutol (2HRZE)"))
story.append(bullet("Continuation phase (4 months): Isoniazid + Rifampicin (4HR)"))
story.append(bullet("Reconstructive surgery for deformity after completion of treatment"))
story.append(sp())

# Q5b — Tropical Ulcer
story.append(sub_header("Q5b) TROPICAL ULCER"))
story.append(p(
    "<b>Definition:</b> Tropical ulcer (also known as Aden ulcer, jungle rot, or Naga sore) is "
    "an acute, rapidly developing, painless-to-painful cutaneous ulcer occurring in tropical regions, "
    "primarily affecting the lower limbs. Primarily seen in malnourished individuals in sub-Saharan Africa, "
    "South Asia, and Pacific islands."
))
story.append(p(
    "<b>Aetiology:</b> Polymicrobial — classically associated with <i>Fusobacterium ulcerans</i> "
    "and <i>Treponema vincenti</i> (previously Borrelia vincenti). Minor trauma is the precipitating factor. "
    "Malnutrition, poor hygiene, and immunosuppression are predisposing factors."
))
story.append(sub("Clinical Features"))
story.append(bullet("Site: Lower third of leg, especially around the ankle"))
story.append(bullet("Onset: Papule or pustule after minor trauma → rapidly ulcerates within days"))
story.append(bullet("Ulcer characteristics: Punched-out, circular; foul-smelling, undermined edges; "
                    "grey-brown necrotic slough base; surrounding erythema and oedema"))
story.append(bullet("Acute phase: Painful, rapid expansion, systemic upset"))
story.append(bullet("Chronic phase: Less painful; fibrous, indurated edges; may reach 10–15 cm"))
story.append(bullet("Complications: Secondary infection, osteomyelitis, squamous cell carcinoma "
                    "(Marjolin's ulcer) in long-standing lesions (10–25 year latency)"))
story.append(sub("Investigations"))
story.append(bullet("Swab culture; dark-ground microscopy for spirochaetes"))
story.append(bullet("Biopsy to exclude malignant transformation"))
story.append(bullet("X-ray if osteomyelitis suspected"))
story.append(sub("Management"))
story.append(bullet("Nutritional support: High protein diet, vitamins"))
story.append(bullet("Wound care: Saline wash, debridement, daily dressings"))
story.append(bullet("Antibiotics: Penicillin (crystalline) + Metronidazole for acute phase; "
                    "Amoxicillin for oral maintenance"))
story.append(bullet("Skin grafting: Split-thickness skin graft (STSG) for large ulcers after "
                    "achieving clean bed"))
story.append(bullet("Surgery for malignant transformation"))
story.append(sp())

# Q5c — Fistula
story.append(sub_header("Q5c) FISTULA"))
story.append(p(
    "<b>Definition:</b> A fistula is an <b>abnormal communication between two epithelium-lined "
    "surfaces</b>. The tract is usually lined by granulation tissue, which may become epithelialised "
    "in chronic cases. Fistulae are either congenital or acquired."
))
story.append(sub("Classification"))
story.append(p("<b>By aetiology:</b>"))
story.append(bullet("<b>Congenital:</b> Tracheo-oesophageal fistula, branchial fistula, "
                    "thyroglossal fistula, vesicouterine fistula"))
story.append(bullet("<b>Acquired:</b> Inflammatory (Crohn's disease, diverticulitis), post-surgical, "
                    "malignant, traumatic, radiation-induced, infective (actinomycosis)"))
story.append(p("<b>By anatomy:</b>"))
story.append(bullet("<b>External (cutaneous) fistula:</b> Opens onto skin surface — "
                    "e.g. enterocutaneous fistula, orocutaneous"))
story.append(bullet("<b>Internal fistula:</b> Between two hollow organs — "
                    "e.g. colovesical (faecaluria, pneumaturia), colovaginal, biliary-enteric"))
story.append(p("<b>By output (enterocutaneous fistulae):</b>"))
story.append(bullet("Low output: &lt;200 mL/24h — usually colonic; easier to manage"))
story.append(bullet("Moderate output: 200–500 mL/24h"))
story.append(bullet("High output: &gt;500 mL/24h — usually small bowel; metabolic consequences severe"))
story.append(sub("Conditions Preventing Spontaneous Closure (FRIENDS)"))
story.append(p(
    "<b>F</b>oreign body in tract | <b>R</b>adiation damage | <b>I</b>nflammation/Infection | "
    "<b>E</b>pithelialization of tract | <b>N</b>eoplasm | <b>D</b>istal obstruction | "
    "<b>S</b>hort tract (&lt;2 cm) / <b>S</b>teroids"
))
story.append(sub("Management Principles"))
story.append(bullet("<b>Resuscitation:</b> Correct fluid/electrolyte deficit — especially in "
                    "high-output small bowel fistulae"))
story.append(bullet("<b>Nutrition:</b> TPN often required; reduce GI secretions"))
story.append(bullet("<b>Sepsis control:</b> Drain collections; antibiotics as needed"))
story.append(bullet("<b>Skin protection:</b> Stoma appliances, barrier creams for effluent protection"))
story.append(bullet("<b>Conservative:</b> 30–40% close spontaneously if no 'FRIENDS' factors, "
                    "usually within 4–6 weeks"))
story.append(bullet("<b>Surgical:</b> Resection + primary anastomosis; bypass; diversion stoma"))
story.append(bullet("<b>Somatostatin analogues</b> (octreotide) reduce fistula output in "
                    "selected cases"))
story.append(sp())

# Q5d — Hidradenitis Suppurativa
story.append(sub_header("Q5d) HIDRADENITIS SUPPURATIVA (HS)"))
story.append(p(
    "<b>Definition:</b> Hidradenitis suppurativa is a chronic, recurrent, debilitating inflammatory "
    "skin disease of the apocrine gland-bearing skin, characterised by painful nodules, abscesses, "
    "sinus tracts, and scarring."
))
story.append(p(
    "<b>Pathogenesis:</b> Primarily a disease of follicular occlusion (not a primary apocrine "
    "gland disorder as once thought). Follicular hyperkeratosis → occlusion of hair follicle → "
    "bacterial superinfection (Staph. aureus, Streptococcus) → rupture → intense inflammatory response → "
    "abscess → chronic sinus tract formation → scarring."
))
story.append(p(
    "<b>Risk factors:</b> Obesity, smoking, diabetes, family history (30–40% have first-degree "
    "relative), hormonal factors (worse perimenstrually)."
))
story.append(sub("Sites"))
story.append(bullet("Axillae (most common), groins, perineum, buttocks, inframammary region, "
                    "inner thighs"))
story.append(sub("Hurley Staging"))
story.append(bullet("<b>Stage I:</b> Abscess formation, single or multiple, without sinus tracts "
                    "or cicatrization"))
story.append(bullet("<b>Stage II:</b> Recurrent abscesses with tract formation and scarring; "
                    "single or multiple widely separated lesions"))
story.append(bullet("<b>Stage III:</b> Diffuse or near-diffuse involvement; multiple interconnected "
                    "tracts and abscesses; entire area affected"))
story.append(sub("Management"))
story.append(p("<b>Medical:</b>"))
story.append(bullet("Antibiotics: Topical clindamycin; systemic tetracyclines (doxycycline), "
                    "clindamycin + rifampicin combination"))
story.append(bullet("Anti-androgens: Combined OCP, spironolactone (in women)"))
story.append(bullet("Biologics: <b>Adalimumab</b> (anti-TNF-α) — only FDA-approved biologic for HS; "
                    "Secukinumab (IL-17A inhibitor) recently approved"))
story.append(bullet("Intralesional steroids: For acute flares"))
story.append(p("<b>Surgical:</b>"))
story.append(bullet("Incision and drainage: For acute painful abscesses (relieves pain but does "
                    "not prevent recurrence)"))
story.append(bullet("Deroofing/unroofing: Excision of roof of sinus tracts; low recurrence"))
story.append(bullet("Wide local excision: Definitive treatment for Stage III; extends to healthy "
                    "tissue; wound left to heal by secondary intention or STSG"))
story.append(sp())

# Q5e — Zollinger-Ellison Syndrome
story.append(sub_header("Q5e) ZOLLINGER–ELLISON SYNDROME (ZES)"))
story.append(p(
    "<b>Definition:</b> Zollinger–Ellison syndrome is a condition characterised by gastric acid "
    "hypersecretion due to a gastrin-secreting tumour (<b>gastrinoma</b>), causing recurrent "
    "severe peptic ulcers, diarrhoea, and oesophagitis. Described by Zollinger and Ellison in 1955."
))
story.append(p(
    "<b>Epidemiology:</b> Rare (1–3 per million/year). Most cases sporadic; ~25% associated with "
    "<b>MEN-1</b> (multiple endocrine neoplasia type 1 — parathyroid, pituitary, pancreatic tumours)."
))
story.append(sub("Gastrinoma Triangle"))
story.append(p(
    "~90% of gastrinomas are located within the <b>gastrinoma triangle</b>:"
))
story.append(bullet("Superior border: Junction of cystic duct and common bile duct"))
story.append(bullet("Inferior border: Junction of 2nd and 3rd parts of duodenum"))
story.append(bullet("Medial border: Junction of head and neck of pancreas"))
story.append(p(
    "Within the triangle: <b>Duodenum</b> (45–60% of tumours) > Pancreatic head > "
    "Lymph nodes. Most are malignant (60%) with lymph node metastases."
))
story.append(sub("Clinical Features"))
story.append(bullet("Peptic ulcer disease — severe, recurrent, often multiple, "
                    "atypical locations (post-bulbar, jejunum)"))
story.append(bullet("Diarrhoea (50–60%) — from acid inactivating pancreatic enzymes and "
                    "damaging small bowel mucosa; resolves with acid suppression"))
story.append(bullet("Oesophagitis — from massive acid reflux"))
story.append(bullet("Abdominal pain — prominent and severe"))
story.append(bullet("Hypertrophic gastric folds on endoscopy"))
story.append(sub("Investigations"))
story.append(bullet("<b>Fasting serum gastrin</b> (&gt;1000 pg/mL with gastric pH &lt;2 — diagnostic)"))
story.append(bullet("<b>Basal acid output (BAO)</b>: >15 mEq/h (or >5 in post-gastrectomy patients)"))
story.append(bullet("<b>Secretin stimulation test:</b> IV secretin → paradoxical rise in gastrin "
                    "(&gt;200 pg/mL increase) — most sensitive provocative test"))
story.append(bullet("Imaging: CT/MRI, endoscopic ultrasound (EUS — most sensitive), "
                    "68Ga-DOTATATE PET-CT (somatostatin receptor scintigraphy)"))
story.append(sub("Management"))
story.append(p("<b>Medical:</b>"))
story.append(bullet("High-dose <b>Proton Pump Inhibitors</b> (PPIs): Omeprazole 40–120 mg/day; "
                    "controls acid hypersecretion; first-line"))
story.append(bullet("Somatostatin analogues (octreotide): Reduces gastrin secretion; "
                    "used for metastatic disease"))
story.append(p("<b>Surgical:</b>"))
story.append(bullet("Curative resection if tumour localised and no MEN-1"))
story.append(bullet("In MEN-1: Surgery deferred unless tumour >2 cm (MEN-1 gastrinomas are "
                    "multiple and diffuse)"))
story.append(bullet("Liver metastases: Resection, ablation, hepatic artery embolisation"))
story.append(p("<b>Prognosis:</b> 5-year survival ~65–80% for localised disease; "
               "~30% for disease with liver metastases. MEN-1 associated ZES has better prognosis."))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# Q6 — Emergency Management of Burns (10 marks)
# ══════════════════════════════════════════════════════════════════════════════
story.append(q_header(6, 10,
    "Emergency Management of a Burns Victim"))
story.append(sp())

story.append(p(
    "Burns are a major cause of trauma, morbidity, and mortality worldwide. "
    "Effective emergency management within the 'golden hour' significantly improves outcomes "
    "by preventing systemic complications including shock, inhalation injury, and sepsis. "
    "Management follows the standard <b>ATLS (Advanced Trauma Life Support)</b> principles."
))
story.append(sp(0.1))
story.append(sub_header("STEP-BY-STEP EMERGENCY MANAGEMENT FLOWCHART"))
story.append(sp(0.1))
for fl in flowchart_burns():
    story.append(fl)
story.append(sp(0.2))

story.append(sub("1. Scene Safety and Stopping the Burning Process"))
story.append(bullet("Remove patient from burning source; stop smouldering clothing"))
story.append(bullet("Chemical burns: Brush off dry chemical first; copious water irrigation "
                    "≥20 minutes (do not use antidotes)"))
story.append(bullet("Electrical burns: Isolate power supply before touching patient"))
story.append(bullet("Cool the burn with tepid water (15–25°C) for 20 minutes — reduces depth "
                    "of burn and pain. Do NOT use ice (causes vasoconstriction and worsens injury)."))

story.append(sub("2. Primary Survey (ABCDE)"))
story.append(p("<b>A — Airway (with C-spine control if trauma):</b>"))
story.append(bullet("Signs of airway compromise: Stridor, hoarseness, facial burns, "
                    "singed nasal hair, soot in mouth/nares, blistering in oropharynx"))
story.append(bullet("Early intubation if any inhalation injury suspected "
                    "(oedema develops rapidly — delay makes intubation impossible)"))
story.append(bullet("100% oxygen via non-rebreather mask for all significant burns"))
story.append(p("<b>B — Breathing:</b>"))
story.append(bullet("Assess respiratory rate, oxygen saturation, chest movement"))
story.append(bullet("Circumferential chest burns → escharotomy if respiratory compromise"))
story.append(bullet("CO poisoning: treat with 100% O₂ until COHb &lt;5%; "
                    "consider hyperbaric O₂ if levels >25%"))
story.append(p("<b>C — Circulation:</b>"))
story.append(bullet("Two large-bore IV cannulae (14–16G) through unburned skin if possible"))
story.append(bullet("Begin fluid resuscitation; draw bloods (FBC, U&E, glucose, group+screen, "
                    "lactate, COHb, ABG)"))
story.append(p("<b>D — Disability (Neurological):</b>"))
story.append(bullet("Assess GCS; analgesia (IV morphine 0.1 mg/kg titrated)"))
story.append(p("<b>E — Exposure:</b>"))
story.append(bullet("Full exposure to assess all burns; maintain warmth (hypothermia worsens coagulopathy)"))

story.append(sub("3. Assessment of Burn Severity"))
story.append(p("<b>a) Total Body Surface Area (%TBSA) — Rule of Nines:</b>"))
story.append(rule_of_nines_table())
story.append(sp(0.1))
story.append(p("Palm rule: Patient's palm (fingers closed) = approximately 1% TBSA. "
               "Useful for patchy burns."))
story.append(sp(0.1))
story.append(p("<b>b) Depth Assessment:</b>"))
story.append(bullet("<b>Superficial (1st degree):</b> Epidermis only; erythema, pain, no blistering "
                    "(e.g. sunburn) — not included in TBSA calculation for resuscitation"))
story.append(bullet("<b>Superficial partial-thickness (2nd degree):</b> Epidermis + superficial dermis; "
                    "blistering, moist, extremely painful, pink/red, brisk capillary refill"))
story.append(bullet("<b>Deep partial-thickness (2nd degree):</b> Deep dermis involved; "
                    "reduced/absent pain, white/yellow, delayed capillary refill"))
story.append(bullet("<b>Full-thickness (3rd degree):</b> All dermis destroyed; leathery, pale/brown/black, "
                    "painless, no blistering, does not blanch; requires grafting"))
story.append(bullet("<b>4th degree:</b> Extends to muscle, bone, tendon — electrical burns common cause"))

story.append(sub("4. Fluid Resuscitation — Parkland Formula"))
story.append(info_box(
    "PARKLAND FORMULA (Gold Standard)",
    [
        "Total fluid in 24 hours = 4 mL × weight (kg) × %TBSA burned",
        "Fluid: Hartmann's solution (Ringer's lactate) — CRYSTALLOID",
        "HALF given in first 8 hours (from time of burn, NOT time of presentation)",
        "Remaining HALF given over next 16 hours",
        "Monitor: Urine output via urinary catheter — target 0.5 mL/kg/h (adults), 1 mL/kg/h (children)",
        "Example: 70 kg adult with 30% TBSA = 4×70×30 = 8400 mL; 4200 mL in first 8h, 4200 mL in next 16h",
        "Colloid (albumin) added after 8–12 hours in burns >40% TBSA",
    ],
    bg=colors.HexColor("#E8F5E8"),
    tc=GREEN
))
story.append(sp(0.1))
story.append(p(
    "<b>Resuscitation endpoint:</b> Urine output is the most reliable indicator. "
    "Avoid over-resuscitation ('fluid creep') — causes abdominal compartment syndrome and pulmonary oedema."
))

story.append(sub("5. Wound Management"))
story.append(bullet("Cover burns with clean cling film (non-adherent, transparent for monitoring, "
                    "reduces pain by keeping air from wound)"))
story.append(bullet("Do NOT apply butter, toothpaste, or other home remedies"))
story.append(bullet("Do NOT burst blisters in emergency setting"))
story.append(bullet("Formal wound cleaning and dressing in a controlled environment"))

story.append(sub("6. Additional Emergency Measures"))
story.append(bullet("<b>Analgesia:</b> IV morphine titrated; avoid intramuscular injections "
                    "(poor absorption due to peripheral shutdown)"))
story.append(bullet("<b>Nasogastric tube:</b> Insert if burns >20% TBSA (ileus expected; "
                    "Curling's ulcer prophylaxis with PPI/H2 blocker; early enteral nutrition)"))
story.append(bullet("<b>Tetanus prophylaxis:</b> Administer if not up to date"))
story.append(bullet("<b>Urinary catheter:</b> For monitoring fluid balance in burns >15–20% TBSA"))
story.append(bullet("<b>Escharotomy:</b> For circumferential full-thickness burns of limbs "
                    "(compartment syndrome) or chest (respiratory compromise); "
                    "medial and lateral incisions through eschar"))
story.append(bullet("<b>Bloods:</b> FBC, U&E, LFTs, clotting, group &amp; screen, ABG, COHb, lactate"))
story.append(bullet("<b>Warming:</b> Maintain normothermia — burned patients lose heat rapidly"))

story.append(sub("7. Criteria for Transfer to Burns Unit"))
story.append(info_box(
    "Refer to specialist burns unit if:",
    [
        "Burns >10% TBSA in adults; >5% in children",
        "Any full-thickness burn",
        "Burns involving face, hands, feet, genitalia, perineum, or major joints",
        "Circumferential burns",
        "Inhalation injury",
        "Chemical or electrical burns",
        "Burns with significant co-morbidity",
        "Suspected non-accidental injury (children)",
    ],
    bg=colors.HexColor("#FFF3E0"),
    tc=GOLD
))
story.append(sp(0.2))
story.append(p(I("Reference: Bailey &amp; Love's Short Practice of Surgery, 28th ed., Chapter 46 (Burns). "
                 "Schwartz's Principles of Surgery, 11th ed.")))

# ─── Final reference footer ──────────────────────────────────────────────────
story.append(sp(0.5))
story.append(HRFlowable(width="100%", thickness=1, color=GOLD))
story.append(sp(0.1))
story.append(Paragraph(
    "<b>References:</b> Bailey &amp; Love's Short Practice of Surgery 28th ed. | "
    "Sabiston Textbook of Surgery 21st ed. | Schwartz's Principles of Surgery 11th ed. | "
    "Robbins &amp; Kumar Basic Pathology | Cummings Otolaryngology Head and Neck Surgery | "
    "Andrews' Diseases of the Skin | Fischer's Mastery of Surgery 8th ed.",
    ref_style
))

# ─── Build ──────────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(BLUE)
    canvas.rect(doc.leftMargin - 0.2*cm, H - 1.5*cm,
                W - doc.leftMargin - doc.rightMargin + 0.4*cm, 0.6*cm, fill=1, stroke=0)
    canvas.setFont("Helvetica-Bold", 8)
    canvas.setFillColor(colors.white)
    canvas.drawString(doc.leftMargin, H - 1.2*cm, "MBBS Phase 3 Part 2 — Surgery Paper 1 — Model Answers")
    canvas.drawRightString(W - doc.rightMargin, H - 1.2*cm, "Reference: Bailey & Love | Sabiston | Schwartz")
    # Footer
    canvas.setFillColor(colors.grey)
    canvas.setFont("Helvetica", 7.5)
    canvas.drawCentredString(W/2, 1.2*cm, f"Page {doc.page}")
    canvas.setLineWidth(0.5)
    canvas.setStrokeColor(GOLD)
    canvas.line(doc.leftMargin, 1.5*cm, W - doc.rightMargin, 1.5*cm)
    canvas.restoreState()

doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print("PDF generated successfully.")
Running Command

cd /tmp/workspace/surgery-paper && python generate_pdf.py 2>&1

Editing File

~/surgery-paper/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/tmp/workspace/surgery-paper/generate_pdf.py'
Running Command

cd /tmp/workspace/surgery-paper && python generate_pdf.py 2>&1

Running Command

ls -lh /tmp/workspace/surgery-paper/MBBS_Surgery_Answers.pdf

Your PDF is ready! Here's the download link:

MBBS Surgery Answers

PDF Document · PDF


What's inside the PDF

The document is a beautifully formatted, multi-page A4 PDF with a professional blue/gold colour scheme, page headers, footers with page numbers, and styled section boxes. Here's what each question covers:

Q2 (20 marks) — Surgical Anatomy of Thyroid + Thyroiditis
  • Full surgical anatomy: shape, weight, capsule (Berry's ligament), blood supply (all 4 arteries + 3 veins), nerve relations (RLN, EBSLN, Tubercle of Zuckerkandl), parathyroids, lymphatics, and embryology
  • Thyroiditis table comparing 6 types: Hashimoto's, De Quervain's, Painless/Silent, Riedel's, Acute Suppurative, Radiation-induced — with features and management
Q3 (5 marks each) — Short Notes
  • Lipoma: Definition, all 10+ types (angiolipoma, hibernoma, pleomorphic, etc.), treatment
  • Neurofibroma: Types, NF-1 diagnostic criteria (NIH), complications, selumetinib
  • TPN: Indications, all components (carbs/lipid/amino acids/electrolytes/vitamins/trace elements), monitoring, complications (refeeding syndrome, IFALD)
  • Compartment Syndrome: Aetiology, pathophysiology, 6 Ps, diagnosis (delta P formula), fasciotomy
  • Keloid: Pathology, Keloid vs Hypertrophic Scar comparison table, full treatment ladder
Q4 (5 marks each) — Explain Why
  • Small intestine malignancy rare: 7 reasons (rapid transit, alkaline pH, GALT/IgA, low bacteria, rapid turnover, benzpyrene hydroxylase, liquid content)
  • Appendicitis in children and elderly: Detailed mechanistic reasons for each group (thin wall, small omentum, immunosenescence, atypical presentation, high perforation rate)
Q5 (5 marks each) — Short Notes
  • Lupus Vulgaris: Apple-jelly sign, histology, anti-TB regimen (2HRZE/4HR)
  • Tropical Ulcer: Fusobacterium/Treponema aetiology, management, Marjolin's ulcer
  • Fistula: Classification, FRIENDS mnemonic (factors preventing closure), management
  • Hidradenitis Suppurativa: Hurley staging (I–III), medical + surgical management, adalimumab
  • Zollinger–Ellison Syndrome: Gastrinoma triangle anatomy, secretin test, PPIs, surgical criteria
Q6 (10 marks) — Emergency Burns Management
  • 9-step colour-coded flowchart from scene safety to transfer criteria
  • Rule of Nines table (adults vs Lund-Browder for children)
  • Parkland Formula highlighted in a green info box with worked example
  • Burn depth classification, escharotomy, fluid monitoring, burns unit referral criteria
This is a shared conversation. Sign in to Orris to start your own chat.