liver cirrOsis apporoach diagnosis mANAGEMENT AND TREATMENT

Reading File
Finding Sources
Finding Sources
Searching PubMed

"liver cirrhosis"[MeSH Terms] AND management

Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Finding Sources
Reading File
Loading Image
I now have comprehensive information to deliver a detailed, well-structured answer. Let me compile it.

Liver Cirrhosis: Approach, Diagnosis, Management & Treatment


Definition & Pathology

Cirrhosis is the end stage of any chronic liver disease, defined as the diffuse transformation of the entire liver into regenerative parenchymal nodules surrounded by fibrous bands. Critically:
  • Not all chronic liver disease terminates in cirrhosis
  • Not all cirrhosis leads to end-stage liver failure (e.g., treated autoimmune hepatitis, cured hepatitis C may retain adequate function despite cirrhosis)
  • Regression of fibrosis - and even established cirrhosis - is possible with disease remission or cure
Gross & Microscopic Appearance (Goldman-Cecil Medicine, Figure 139-1):
Normal vs. cirrhotic liver - gross and microscopic pathology
A: Normal liver - smooth surface, homogeneous texture. B: Normal histology - organized sinusoids. C: Cirrhotic liver - orange-tawny color, irregular nodular surface. D: Cirrhotic histology - disorganized architecture, regenerative nodules surrounded by fibrous tissue.

Pathogenesis

The key pathogenic mechanism is activation of hepatic stellate cells (Ito cells / perisinusoidal cells):
  • Normally quiescent, located in the space of Disse between hepatocytes and sinusoidal endothelial cells; serve as vitamin A storage
  • On injury: lose vitamin A, proliferate, develop rough ER, secrete extracellular matrix (collagen types I & III, sulfated proteoglycans, glycoproteins), and transform into contractile myofibroblasts
Collagen deposition in the space of Disse leads to defenestration of sinusoidal endothelial cells ("capillarization" of sinusoids), reducing sinusoidal diameter and impairing exchange between plasma and hepatocytes.

Etiology (Causes of Cirrhosis)

Main causes (>90% of cases):
CauseNotes
Alcoholic liver diseaseLeading cause in Western countries
Non-alcoholic fatty liver disease (NAFLD/MASLD)Increasingly prevalent
Chronic hepatitis BLeading cause worldwide
Chronic hepatitis C
Other causes (<2% each):
  • Cholestatic/autoimmune: Primary biliary cholangitis (PBC), Primary sclerosing cholangitis (PSC), Autoimmune hepatitis
  • Metabolic: Hemochromatosis, Wilson disease, α1-antitrypsin deficiency, Glycogen storage diseases, Porphyria
  • Vascular: Budd-Chiari syndrome, Veno-occlusive disease, Right-sided heart failure
  • Biliary obstruction: Biliary atresia, Cystic fibrosis
  • Drugs and toxins, Intestinal bypass
  • Cryptogenic cirrhosis - no clear cause identified

Classification: Compensated vs. Decompensated

StageDefinitionKey Features
CompensatedNo complications yetMay be asymptomatic; ~40% of patients
DecompensatedOne or more complications developedAscites, variceal hemorrhage, hepatic encephalopathy, or jaundice
Decompensation is the key prognostic inflection point. Once decompensation occurs, prognosis significantly worsens regardless of scoring system used.

Clinical Features

Symptoms (may be absent until advanced stages):

  • Anorexia, weight loss, weakness
  • Fatigue, muscle wasting (sarcopenia)
  • Abdominal discomfort, distension (ascites)
  • Jaundice, pruritus (from cholestasis)

Physical Examination - Stigmata of Cirrhosis:

  • Muscle atrophy: bitemporal, thenar/hypothenar (marker of liver insufficiency)
  • Spider angiomas: on trunk, face, upper limbs (markers of vasodilation)
  • Palmar erythema: thenar/hypothenar and fingertips
  • Gynecomastia, testicular atrophy, hair loss on chest/abdomen (in men)
  • Petechiae and ecchymoses: thrombocytopenia or prolonged PT
  • Caput medusae: dilated periumbilical veins
  • Splenomegaly
  • Asterixis (flapping tremor): hallmark of overt hepatic encephalopathy
  • Fetor hepaticus: sweet-smelling breath in encephalopathy

Two Main Consequences of Cirrhosis

1. Portal Hypertension + Hyperdynamic Circulatory State

  • Results from increased resistance to portal flow (fixed component: fibrosis/nodules + functional component: vasoconstriction due to intrahepatic nitric oxide deficiency) AND increased portal inflow (splanchnic vasodilation)
  • Leads to: varices, ascites, hypersplenism

2. Liver Insufficiency

  • Leads to: jaundice (inability to excrete bilirubin), coagulopathy
  • Encephalopathy results from both mechanisms

Complications

Ascites

  • Most common complication of portal hypertension
  • Results from combination of portal hypertension, hypoalbuminemia, lymphatic leakage, and sodium retention

Spontaneous Bacterial Peritonitis (SBP)

  • Most common bacterial infection in cirrhosis
  • Clinical features: fever, jaundice, abdominal pain/tenderness, rebound; up to 1/3 may be asymptomatic
  • Diagnosis: ascitic fluid PMN count >250 cells/μL
  • Most common organisms: gram-negative enteric bacteria (monobacterial)
  • Anaerobes, fungi, or polymicrobial infection should raise suspicion of secondary bacterial peritonitis

Hepatic Encephalopathy (HE)

  • Incidence ~2-3% per year in cirrhosis
  • Grades:
    • Grade 1: Inversion of sleep-wake pattern, forgetfulness, distal tremor
    • Grade 2: Confusion, bizarre behavior, disorientation
    • Grade 3: Lethargy, profound disorientation
    • Grade 4: Coma
  • Minimal HE: present in up to 80% of cirrhotic patients; diagnosed by psychometric tests only
  • Ammonia levels unreliable (levels >150 μmol/L are indicative but not diagnostic)
  • EEG: generalized slow waves, triphasic waves

Hepatorenal Syndrome (HRS)

  • Functional renal failure - diagnosis of exclusion
  • Typically accompanied by ascites unresponsive to diuretics and hyponatremia
  • Differential: sepsis, over-diuresis, GI hemorrhage, NSAIDs, aminoglycosides
  • Diagnosis only after: diuretics stopped, contributing factors treated, and intravascular volume expanded with albumin

Pulmonary Complications

  • Hepatopulmonary syndrome (HPS): exertional dyspnea, clubbing, cyanosis, vascular spiders; present in ~5-10% awaiting transplant
    • Diagnosis: PaO2 <80 mmHg or A-a gradient >15 mmHg + pulmonary vascular shunting on contrast echocardiography
  • Portopulmonary hypertension: exertional dyspnea, syncope, chest pain; accentuated P2, RV heave

Hepatocellular Carcinoma (HCC)

  • Cirrhosis is the major risk factor; surveillance with ultrasound ± AFP every 6 months is standard

Diagnosis

Clinical Diagnosis

  • Suspected in any patient with chronic liver disease
  • Physical examination may be normal in compensated cirrhosis

Laboratory Tests

  • Liver function tests: elevated bilirubin, AST/ALT (note: AST:ALT >1 in alcoholic liver disease; AST rarely >300 IU/L in ALD)
  • Synthetic function: prolonged PT/INR, low albumin
  • CBC: thrombocytopenia (hypersplenism), anemia
  • GGT: elevated, particularly in alcoholic disease
  • Serum bilirubin and INR typically normal in early steatosis; elevated in decompensation

Imaging

  • Ultrasound: irregular liver surface, nodularity, splenomegaly, ascites
  • CT/MRI: detailed assessment; a 2026 systematic review (PMID 41882492) highlights the need for standardization of imaging-based morphological criteria for cirrhosis
  • Liver stiffness measurement (elastography): non-invasive assessment of fibrosis

Liver Biopsy

  • Gold standard for diagnosis of cirrhosis
  • Invasive, subject to sampling error; can often be replaced by non-invasive methods

Scoring Systems for Prognosis

Child-Pugh Classification:
Parameter1 point2 points3 points
Bilirubin<2 mg/dL2-3 mg/dL>3 mg/dL
Albumin>3.5 g/dL2.8-3.5 g/dL<2.8 g/dL
PT/INR<1.71.7-2.3>2.3
AscitesNoneMildModerate/severe
EncephalopathyNoneGrade 1-2Grade 3-4
  • Class A (5-6 pts): Compensated; Class B (7-9 pts): Decompensation begins; Class C (≥10 pts): Advanced/decompensated
MELD Score: Uses bilirubin + INR + creatinine - more accurate than Child-Pugh for predicting survival; now primary tool for transplant organ allocation. Originally designed to assess prognosis of cirrhotic patients undergoing TIPS.

Management & Treatment

General Principles

  1. Treat the underlying etiology (alcohol cessation, antivirals for HBV/HCV, metabolic optimization for NAFLD, chelation for hemochromatosis, etc.)
  2. Prevent decompensation
  3. Manage complications when they develop
  4. Screen for HCC (ultrasound every 6 months)
  5. Evaluate for liver transplantation in advanced disease

Management of Ascites

  • Step 1: Sodium restriction - 2 g/day (88 mmol/day)
  • Step 2: Diuretics when sodium restriction alone is inadequate:
    • Spironolactone (first-line, potassium-sparing): 100 mg/day; can control up to 50% of cirrhotic ascites alone; higher doses (100 mg+) very effective
    • Furosemide (loop diuretic): added in combination; standard ratio is furosemide 40 mg : spironolactone 100 mg to maintain potassium homeostasis
    • No evidence that metolazone, thiazides, bumetanide, or torsemide offer advantage over this combination
  • Large-volume paracentesis: for tense or refractory ascites; always with albumin infusion (8 g/L ascites removed) to prevent post-paracentesis circulatory dysfunction
  • TIPS: for refractory ascites not controlled by diuretics and repeated paracentesis

Management of Varices and Variceal Bleeding

Primary Prophylaxis (prevention of first bleed):

  • Carvedilol (non-selective β-blocker with vasodilating properties): 3.125-12.5 mg/day - now preferred; more effective than other β-blockers for portal pressure reduction; reduces decompensation and death in compensated cirrhosis with significant portal hypertension
  • Propranolol or nadolol (non-selective β-blockers): significantly reduce first variceal hemorrhage in patients with medium/large varices
  • Endoscopic variceal ligation (EVL): at least as effective as non-selective β-blockers for primary prophylaxis; used when β-blockers are contraindicated or not tolerated; does NOT prevent ascites
Endoscopy surveillance:
  • No varices: repeat EGD every 2-3 years
  • Small varices: repeat EGD every 1-2 years
  • Decompensated disease: sooner (before varices grow and bleed)

Acute Variceal Hemorrhage:

  1. ICU resuscitation - avoid over-transfusion; target Hb ~8 g/dL (over-transfusion can precipitate rebleeding)
  2. Prophylactic antibiotics: ceftriaxone 1 g/day IV for 5-7 days (reduces bacterial infections AND rebleeding and death)
  3. Vasoconstrictors (initiate at admission, continue 2-5 days):
    • Terlipressin, somatostatin, octreotide, or vapreotide
    • In the US: octreotide - 50 μg IV bolus then 50 μg/hour infusion
  4. Endoscopic variceal ligation (preferred endoscopic therapy)
  5. If standard therapy fails: TIPS (transjugular intrahepatic portosystemic shunt)
  6. "Early" preemptive TIPS (within 24-48 hours): recommended for high-risk patients - Child C (score 10-13) and Child B patients with active bleeding at endoscopy - significantly reduces failure and improves survival
  7. Esophageal stent: bridge to definitive therapy when bleeding continues despite vasoconstrictors + ligation (safer than balloon tamponade)

Secondary Prophylaxis (after first bleed):

  • Combination of non-selective β-blocker + EVL

Management of Spontaneous Bacterial Peritonitis (SBP)

  • Empiric antibiotics: 3rd-generation cephalosporins (e.g., cefotaxime or ceftriaxone) are first-line
  • IV albumin: 1.5 g/kg at diagnosis and 1 g/kg on day 3 - reduces renal impairment and mortality
  • Primary prophylaxis: norfloxacin or trimethoprim-sulfamethoxazole in high-risk patients (low ascitic protein, prior SBP episode)
  • Note: increasing prevalence of multidrug-resistant organisms due to widespread antibiotic use

Management of Hepatic Encephalopathy

Aims to reduce nitrogenous waste production and intestinal bacterial metabolic activity:
  1. Identify and treat precipitating factors: GI bleeding, infection, electrolyte imbalance, constipation, sedatives, renal failure, excessive dietary protein
  2. Lactulose (first-line): 15-45 mL PO bid-qid (or NG tube); reduces intestinal ammonia absorption; target 2-3 soft stools/day
  3. Rifaximin: added when lactulose alone is insufficient; rifaximin + lactulose combination significantly superior to lactulose alone (49.1% vs lactulose response rate in trials); recommended for patients not responding to or intolerant of lactulose
  4. Protein restriction (moderate) in acute severe episodes

Management of Hepatorenal Syndrome

  • Discontinue diuretics and nephrotoxins
  • Expand intravascular volume with IV albumin
  • Vasoconstrictors: terlipressin (preferred where available) or norepinephrine + albumin
  • TIPS may be considered in select patients
  • Definitive treatment: liver transplantation

Liver Transplantation

  • Definitive treatment for end-stage liver disease
  • Indicated for: decompensated cirrhosis (Child-Pugh B/C), MELD ≥15-17, HCC within Milan criteria, HPS
  • Evaluation should begin early in decompensated disease
  • Management of complications (variceal bleeding, ascites, encephalopathy, HCC) does not differ based on cirrhosis etiology - the indications and approach are the same

Summary Table: Key Drug Treatments

ComplicationFirst-lineSecond-line/Add-on
AscitesSpironolactone + sodium restrictionAdd furosemide; paracentesis + albumin for refractory
Variceal prophylaxisCarvedilol (or propranolol/nadolol)Endoscopic variceal ligation
Acute variceal bleedOctreotide + EVL + ceftriaxoneTIPS (preemptive for high-risk)
SBPCefotaxime/ceftriaxone + albuminLong-term norfloxacin prophylaxis
Hepatic encephalopathyLactulose + treat precipitantsAdd rifaximin
Hepatorenal syndromeAlbumin + terlipressinLiver transplant (definitive)

Sources: Goldman-Cecil Medicine (International Ed.), Harrison's Principles of Internal Medicine 22E, Robbins & Kumar Basic Pathology, Yamada's Textbook of Gastroenterology, Washington Manual of Medical Therapeutics, Brenner & Rector's The Kidney, Mulholland & Greenfield's Surgery.
Recent evidence note: A 2026 systematic review (PMID 41882492) calls for standardization of imaging-based morphological criteria for cirrhosis diagnosis, reflecting ongoing refinement of non-invasive diagnostic approaches.

create a quick video on cirrhosis management protocols

Asking for Preferences
Running Command

mkdir -p /home/daytona/workspace/cirrhosis-video && ls /home/daytona/workspace/cirrhosis-video

Writing File

~/cirrhosis-video/cirrhosis_management.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Liver Cirrhosis – Management Protocols</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap');

  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  :root {
    --liver:   #c0392b;
    --liver2:  #e74c3c;
    --dark:    #0d1117;
    --dark2:   #161b22;
    --card:    #1c2330;
    --card2:   #21262d;
    --accent:  #58a6ff;
    --green:   #3fb950;
    --orange:  #f0883e;
    --yellow:  #e3b341;
    --purple:  #bc8cff;
    --text:    #e6edf3;
    --sub:     #8b949e;
    --border:  #30363d;
    --dur: 0.55s;
  }

  html, body {
    width: 100%; height: 100%;
    background: var(--dark);
    font-family: 'Inter', sans-serif;
    color: var(--text);
    overflow: hidden;
  }

  /* ── SLIDE WRAPPER ─────────────────────────────────── */
  #deck {
    position: relative;
    width: 100vw; height: 100vh;
  }

  .slide {
    position: absolute; inset: 0;
    display: flex; flex-direction: column;
    justify-content: center; align-items: center;
    padding: 48px 64px;
    opacity: 0;
    transform: translateX(60px);
    transition: opacity var(--dur) ease, transform var(--dur) ease;
    pointer-events: none;
  }
  .slide.active {
    opacity: 1; transform: translateX(0);
    pointer-events: all;
  }
  .slide.exit {
    opacity: 0; transform: translateX(-60px);
    transition: opacity var(--dur) ease, transform var(--dur) ease;
  }

  /* ── PROGRESS BAR ──────────────────────────────────── */
  #progress-wrap {
    position: fixed; top: 0; left: 0; right: 0;
    height: 4px; background: var(--border); z-index: 100;
  }
  #progress-bar {
    height: 100%;
    background: linear-gradient(90deg, var(--liver), var(--liver2));
    transition: width 0.4s ease;
  }

  /* ── CONTROLS ──────────────────────────────────────── */
  #controls {
    position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%);
    display: flex; align-items: center; gap: 16px;
    background: rgba(22,27,34,0.9);
    border: 1px solid var(--border);
    border-radius: 40px;
    padding: 10px 22px;
    backdrop-filter: blur(12px);
    z-index: 100;
  }
  .btn {
    background: var(--card2); border: 1px solid var(--border);
    color: var(--text); border-radius: 50%;
    width: 38px; height: 38px;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 16px;
    transition: background 0.2s, border-color 0.2s;
  }
  .btn:hover { background: var(--card); border-color: var(--accent); }
  #play-btn { width: 46px; height: 46px; font-size: 18px; background: var(--liver); border-color: var(--liver); }
  #play-btn:hover { background: var(--liver2); }
  #slide-counter { font-size: 13px; color: var(--sub); min-width: 52px; text-align: center; }

  /* timer ring */
  #timer-svg { width: 38px; height: 38px; transform: rotate(-90deg); }
  #timer-circle {
    fill: none; stroke: var(--liver); stroke-width: 3;
    stroke-dasharray: 100; stroke-dashoffset: 100;
    transition: stroke-dashoffset linear;
    stroke-linecap: round;
  }

  /* ── SHARED TYPOGRAPHY ─────────────────────────────── */
  .tag {
    font-size: 11px; font-weight: 700; letter-spacing: 2px;
    text-transform: uppercase; color: var(--liver2);
    margin-bottom: 10px;
  }
  h1 { font-size: clamp(2rem, 5vw, 3.4rem); font-weight: 800; line-height: 1.15; }
  h2 { font-size: clamp(1.4rem, 3.2vw, 2.2rem); font-weight: 700; }
  h3 { font-size: clamp(1rem, 2vw, 1.35rem); font-weight: 600; }
  p, li { font-size: clamp(0.82rem, 1.5vw, 1rem); line-height: 1.7; color: var(--sub); }
  strong { color: var(--text); }

  /* ── DECORATIVE GRID BG ────────────────────────────── */
  .slide::before {
    content: '';
    position: absolute; inset: 0;
    background-image:
      linear-gradient(var(--border) 1px, transparent 1px),
      linear-gradient(90deg, var(--border) 1px, transparent 1px);
    background-size: 50px 50px;
    opacity: 0.18;
    pointer-events: none;
  }

  /* ── CARD GRID ─────────────────────────────────────── */
  .card-grid {
    display: grid;
    gap: 18px;
    width: 100%; max-width: 1100px;
  }
  .cols-2 { grid-template-columns: 1fr 1fr; }
  .cols-3 { grid-template-columns: 1fr 1fr 1fr; }
  .cols-4 { grid-template-columns: 1fr 1fr 1fr 1fr; }

  .card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 20px 22px;
    position: relative;
    overflow: hidden;
  }
  .card .top-bar {
    position: absolute; top: 0; left: 0; right: 0;
    height: 3px;
    border-radius: 14px 14px 0 0;
  }
  .card.red   .top-bar { background: var(--liver2); }
  .card.blue  .top-bar { background: var(--accent); }
  .card.green .top-bar { background: var(--green); }
  .card.orange .top-bar { background: var(--orange); }
  .card.yellow .top-bar { background: var(--yellow); }
  .card.purple .top-bar { background: var(--purple); }

  .card h3 { margin-bottom: 10px; }
  .card.red   h3 { color: var(--liver2); }
  .card.blue  h3 { color: var(--accent); }
  .card.green h3 { color: var(--green); }
  .card.orange h3 { color: var(--orange); }
  .card.yellow h3 { color: var(--yellow); }
  .card.purple h3 { color: var(--purple); }

  .card ul { list-style: none; }
  .card ul li { padding: 3px 0; }
  .card ul li::before { content: '›  '; }

  /* ── PILL BADGES ───────────────────────────────────── */
  .pill {
    display: inline-block;
    padding: 4px 12px; border-radius: 20px;
    font-size: 12px; font-weight: 600;
  }
  .pill-red    { background: rgba(192,57,43,0.2); color: var(--liver2); }
  .pill-green  { background: rgba(63,185,80,0.18); color: var(--green); }
  .pill-blue   { background: rgba(88,166,255,0.18); color: var(--accent); }
  .pill-orange { background: rgba(240,136,62,0.18); color: var(--orange); }
  .pill-yellow { background: rgba(227,179,65,0.18); color: var(--yellow); }
  .pill-purple { background: rgba(188,140,255,0.18); color: var(--purple); }

  /* ── STEP FLOW ─────────────────────────────────────── */
  .flow {
    display: flex; align-items: stretch; gap: 0;
    width: 100%; max-width: 1000px;
  }
  .flow-step {
    flex: 1;
    background: var(--card); border: 1px solid var(--border);
    border-radius: 12px; padding: 16px 14px;
    text-align: center; position: relative;
  }
  .flow-step .step-num {
    width: 28px; height: 28px; border-radius: 50%;
    background: var(--liver); color: #fff;
    font-size: 13px; font-weight: 700;
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 10px;
  }
  .flow-arrow {
    display: flex; align-items: center;
    color: var(--sub); font-size: 22px; padding: 0 4px;
  }

  /* ── TABLE ─────────────────────────────────────────── */
  .data-table {
    width: 100%; max-width: 980px;
    border-collapse: collapse; font-size: 0.88rem;
  }
  .data-table th {
    background: var(--card2); color: var(--text);
    padding: 10px 14px; text-align: left;
    border-bottom: 2px solid var(--liver);
    font-weight: 600;
  }
  .data-table td {
    padding: 9px 14px; border-bottom: 1px solid var(--border);
    color: var(--sub); vertical-align: top;
  }
  .data-table tr:hover td { background: rgba(255,255,255,0.02); }

  /* ── TITLE SLIDE SPECIFIC ──────────────────────────── */
  #slide-0 { background: radial-gradient(ellipse at 60% 40%, rgba(192,57,43,0.18) 0%, transparent 65%), var(--dark); }
  #slide-0 h1 span { color: var(--liver2); }
  .subtitle { font-size: clamp(1rem, 2vw, 1.2rem); color: var(--sub); margin-top: 14px; max-width: 640px; text-align: center; }
  .badge-row { display: flex; gap: 10px; margin-top: 24px; flex-wrap: wrap; justify-content: center; }

  /* ── LIVER ICON SVG ────────────────────────────────── */
  .liver-icon { width: 80px; height: 80px; margin-bottom: 20px; }

  /* ── SECTION DIVIDER ───────────────────────────────── */
  .divider-slide { background: var(--dark2); }
  .divider-slide h2 { font-size: clamp(1.8rem,4vw,2.8rem); }
  .section-number { font-size: 7rem; font-weight: 800; color: rgba(192,57,43,0.12); line-height:1; margin-bottom: -10px; }

  /* ── WIDE CONTENT ──────────────────────────────────── */
  .content-wrap { width: 100%; max-width: 1100px; }

  /* ── ANIMATED ITEMS (stagger on active) ────────────── */
  .stagger > * {
    opacity: 0; transform: translateY(16px);
    transition: opacity 0.4s ease, transform 0.4s ease;
  }
  .slide.active .stagger > *:nth-child(1) { opacity:1; transform:none; transition-delay:.05s; }
  .slide.active .stagger > *:nth-child(2) { opacity:1; transform:none; transition-delay:.15s; }
  .slide.active .stagger > *:nth-child(3) { opacity:1; transform:none; transition-delay:.25s; }
  .slide.active .stagger > *:nth-child(4) { opacity:1; transform:none; transition-delay:.35s; }
  .slide.active .stagger > *:nth-child(5) { opacity:1; transform:none; transition-delay:.42s; }
  .slide.active .stagger > *:nth-child(6) { opacity:1; transform:none; transition-delay:.50s; }
  .slide.active .stagger > *:nth-child(7) { opacity:1; transform:none; transition-delay:.57s; }

  /* ── FOOTNOTE ──────────────────────────────────────── */
  .footnote { position: absolute; bottom: 72px; right: 64px; font-size: 11px; color: var(--border); }

  /* responsive */
  @media (max-width: 800px) {
    .cols-3, .cols-4 { grid-template-columns: 1fr 1fr; }
    .slide { padding: 32px 28px; }
  }
  @media (max-width: 540px) {
    .cols-2, .cols-3, .cols-4 { grid-template-columns: 1fr; }
    .flow { flex-direction: column; }
    .flow-arrow { display: none; }
  }
</style>
</head>
<body>

<div id="progress-wrap"><div id="progress-bar"></div></div>

<!-- ═══════════════════════════════════════════════════
     SLIDES
═══════════════════════════════════════════════════════ -->
<div id="deck">

  <!-- SLIDE 0 — TITLE -->
  <div class="slide active" id="slide-0">
    <svg class="liver-icon" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="40" cy="40" rx="36" ry="30" fill="rgba(192,57,43,0.15)" stroke="var(--liver2)" stroke-width="1.5"/>
      <path d="M18 35 C20 20, 40 18, 55 28 C68 36, 66 55, 55 58 C45 61, 30 58, 22 50 C15 43, 16 48, 18 35Z" fill="rgba(192,57,43,0.35)" stroke="var(--liver2)" stroke-width="1.8"/>
      <circle cx="34" cy="38" r="4" fill="rgba(192,57,43,0.5)" stroke="var(--liver2)" stroke-width="1"/>
      <circle cx="46" cy="34" r="3" fill="rgba(192,57,43,0.5)" stroke="var(--liver2)" stroke-width="1"/>
    </svg>
    <div class="tag">Medical Education · Hepatology</div>
    <h1 style="text-align:center">Liver <span>Cirrhosis</span><br>Management Protocols</h1>
    <p class="subtitle">A concise, evidence-based guide to diagnosis, staging, and treatment of complications — for medical students</p>
    <div class="badge-row stagger">
      <span class="pill pill-red">Compensated vs Decompensated</span>
      <span class="pill pill-blue">Ascites</span>
      <span class="pill pill-orange">Varices</span>
      <span class="pill pill-green">Encephalopathy</span>
      <span class="pill pill-purple">Transplant</span>
    </div>
    <div class="footnote">Goldman-Cecil · Harrison's 22E · Robbins · Yamada · Washington Manual</div>
  </div>

  <!-- SLIDE 1 — WHAT IS CIRRHOSIS -->
  <div class="slide" id="slide-1">
    <div class="tag">Slide 1 — Definition & Pathogenesis</div>
    <h2 style="margin-bottom:24px">What is Cirrhosis?</h2>
    <div class="card-grid cols-2 content-wrap stagger">
      <div class="card red">
        <div class="top-bar"></div>
        <h3>Definition</h3>
        <ul>
          <li><strong>End stage</strong> of any chronic liver disease</li>
          <li>Diffuse transformation → <strong>regenerative nodules</strong> surrounded by fibrous bands</li>
          <li>Not all chronic liver disease = cirrhosis</li>
          <li>Fibrosis can <strong>partially reverse</strong> with treatment</li>
          <li>Variable prognostic implications depending on etiology</li>
        </ul>
      </div>
      <div class="card blue">
        <div class="top-bar"></div>
        <h3>Pathogenesis — Key Cell</h3>
        <ul>
          <li><strong>Hepatic stellate cells</strong> (Ito / perisinusoidal cells)</li>
          <li>Located in <strong>space of Disse</strong></li>
          <li>Normally: quiescent vitamin A storage</li>
          <li>On injury → activated → lose vitamin A, proliferate</li>
          <li>Secrete <strong>collagen I & III</strong>, become contractile myofibroblasts</li>
          <li>→ Defenestration of sinusoids ("capillarization")</li>
        </ul>
      </div>
      <div class="card orange">
        <div class="top-bar"></div>
        <h3>Top Causes</h3>
        <ul>
          <li>🍺 <strong>Alcohol-related</strong> liver disease</li>
          <li>🫀 <strong>NAFLD / MASLD</strong> (rising #1 in many countries)</li>
          <li>🦠 <strong>Chronic Hepatitis B</strong> (leading worldwide)</li>
          <li>🦠 <strong>Chronic Hepatitis C</strong></li>
          <li>Also: PBC, PSC, Wilson's, Hemochromatosis, α1-AT deficiency</li>
        </ul>
      </div>
      <div class="card green">
        <div class="top-bar"></div>
        <h3>Two Core Consequences</h3>
        <ul>
          <li>① <strong>Portal Hypertension</strong> + hyperdynamic state → varices, ascites, splenomegaly</li>
          <li>② <strong>Liver Insufficiency</strong> → jaundice, coagulopathy</li>
          <li>Encephalopathy = both mechanisms combined</li>
          <li>Ascites can lead to SBP → hepatorenal syndrome</li>
        </ul>
      </div>
    </div>
  </div>

  <!-- SLIDE 2 — STAGING -->
  <div class="slide" id="slide-2">
    <div class="tag">Slide 2 — Staging & Prognosis</div>
    <h2 style="margin-bottom:24px">Staging Cirrhosis</h2>
    <div class="content-wrap stagger">
      <div class="card-grid cols-2" style="margin-bottom:20px">
        <div class="card red">
          <div class="top-bar"></div>
          <h3>Compensated</h3>
          <p style="margin-bottom:8px"><span class="pill pill-green">Stable</span></p>
          <ul>
            <li>~40% may be <strong>asymptomatic</strong></li>
            <li>No ascites, no variceal bleed, no encephalopathy, no jaundice</li>
            <li>Liver largely maintaining function</li>
            <li>Child-Pugh A (score 5-6)</li>
          </ul>
        </div>
        <div class="card red">
          <div class="top-bar"></div>
          <h3>Decompensated</h3>
          <p style="margin-bottom:8px"><span class="pill pill-red">High risk</span></p>
          <ul>
            <li><strong>≥1 complication</strong>: ascites, variceal bleed, encephalopathy, or jaundice</li>
            <li>Prognosis significantly worsens</li>
            <li>Child-Pugh B (7-9) or C (≥10)</li>
            <li>Evaluate for liver transplantation</li>
          </ul>
        </div>
      </div>

      <table class="data-table">
        <thead>
          <tr>
            <th>Parameter</th>
            <th>1 point</th>
            <th>2 points</th>
            <th>3 points</th>
            <th>Score → Class</th>
          </tr>
        </thead>
        <tbody>
          <tr><td><strong>Bilirubin</strong></td><td>&lt;2 mg/dL</td><td>2–3 mg/dL</td><td>&gt;3 mg/dL</td><td rowspan="5" style="vertical-align:middle; text-align:center">
            <strong style="color:var(--green)">A</strong> = 5-6 pts<br>
            <strong style="color:var(--yellow)">B</strong> = 7-9 pts<br>
            <strong style="color:var(--liver2)">C</strong> = ≥10 pts
          </td></tr>
          <tr><td><strong>Albumin</strong></td><td>&gt;3.5 g/dL</td><td>2.8–3.5 g/dL</td><td>&lt;2.8 g/dL</td></tr>
          <tr><td><strong>PT/INR</strong></td><td>&lt;1.7</td><td>1.7–2.3</td><td>&gt;2.3</td></tr>
          <tr><td><strong>Ascites</strong></td><td>None</td><td>Mild</td><td>Moderate/severe</td></tr>
          <tr><td><strong>Encephalopathy</strong></td><td>None</td><td>Grade 1–2</td><td>Grade 3–4</td></tr>
        </tbody>
      </table>
      <p style="margin-top:10px; font-size:13px"><strong>MELD score</strong> (bilirubin + INR + creatinine) is more accurate for predicting survival and is used for transplant organ allocation.</p>
    </div>
  </div>

  <!-- SLIDE 3 — DIAGNOSIS -->
  <div class="slide" id="slide-3">
    <div class="tag">Slide 3 — Diagnosis</div>
    <h2 style="margin-bottom:22px">How to Diagnose Cirrhosis</h2>
    <div class="card-grid cols-3 content-wrap stagger">
      <div class="card blue">
        <div class="top-bar"></div>
        <h3>🩺 Clinical Signs</h3>
        <ul>
          <li>Spider angiomas (trunk, face)</li>
          <li>Palmar erythema</li>
          <li>Bitemporal muscle wasting</li>
          <li>Gynecomastia, testicular atrophy</li>
          <li>Caput medusae</li>
          <li>Splenomegaly</li>
          <li><strong>Asterixis</strong> (HE hallmark)</li>
          <li>Fetor hepaticus</li>
        </ul>
      </div>
      <div class="card yellow">
        <div class="top-bar"></div>
        <h3>🧪 Labs</h3>
        <ul>
          <li>↑ Bilirubin, ↑ GGT, ↑ AST/ALT</li>
          <li>AST:ALT <strong>&gt;1</strong> → alcoholic (AST rarely &gt;300)</li>
          <li>↑ PT/INR (synthetic failure)</li>
          <li>↓ Albumin</li>
          <li>↓ Platelets (hypersplenism)</li>
          <li>NH₃ level unreliable; &gt;150 μmol/L supportive of HE</li>
        </ul>
      </div>
      <div class="card green">
        <div class="top-bar"></div>
        <h3>🔬 Investigations</h3>
        <ul>
          <li><strong>Liver biopsy</strong> — gold standard; invasive</li>
          <li>Ultrasound — nodular surface, splenomegaly, ascites</li>
          <li>CT/MRI — detailed morphology</li>
          <li><strong>Elastography (FibroScan)</strong> — non-invasive stiffness</li>
          <li>EGD — screen for varices</li>
          <li>Ascitic PMN &gt;<strong>250/μL</strong> → SBP</li>
        </ul>
      </div>
    </div>
    <div class="card-grid cols-1 content-wrap" style="margin-top:18px; max-width:700px">
      <div class="card purple">
        <div class="top-bar"></div>
        <h3>📊 HCC Surveillance</h3>
        <p>All cirrhotic patients → <strong>ultrasound ± AFP every 6 months</strong>. Cirrhosis is the major risk factor for HCC.</p>
      </div>
    </div>
  </div>

  <!-- SLIDE 4 — ASCITES -->
  <div class="slide" id="slide-4">
    <div class="tag">Slide 4 — Complication Management: Ascites</div>
    <h2 style="margin-bottom:22px">Ascites Management</h2>
    <div class="content-wrap">
      <div class="flow stagger" style="margin-bottom:24px">
        <div class="flow-step">
          <div class="step-num">1</div>
          <h3 style="color:var(--accent); font-size:0.9rem">Sodium Restriction</h3>
          <p style="font-size:0.82rem">≤2 g/day (88 mmol/day)</p>
        </div>
        <div class="flow-arrow">→</div>
        <div class="flow-step">
          <div class="step-num">2</div>
          <h3 style="color:var(--accent); font-size:0.9rem">Diuretics</h3>
          <p style="font-size:0.82rem"><strong>Spironolactone</strong> 100 mg + <strong>Furosemide</strong> 40 mg<br>Ratio 100:40 maintains K⁺</p>
        </div>
        <div class="flow-arrow">→</div>
        <div class="flow-step">
          <div class="step-num">3</div>
          <h3 style="color:var(--accent); font-size:0.9rem">Refractory Ascites</h3>
          <p style="font-size:0.82rem">Large-volume paracentesis +<br><strong>Albumin 8 g/L removed</strong></p>
        </div>
        <div class="flow-arrow">→</div>
        <div class="flow-step">
          <div class="step-num">4</div>
          <h3 style="color:var(--accent); font-size:0.9rem">TIPS</h3>
          <p style="font-size:0.82rem">Transjugular intrahepatic portosystemic shunt</p>
        </div>
        <div class="flow-arrow">→</div>
        <div class="flow-step">
          <div class="step-num">5</div>
          <h3 style="color:var(--accent); font-size:0.9rem">Transplant</h3>
          <p style="font-size:0.82rem">Definitive treatment</p>
        </div>
      </div>
      <div class="card-grid cols-2 stagger">
        <div class="card red">
          <div class="top-bar"></div>
          <h3>⚠️ Spontaneous Bacterial Peritonitis (SBP)</h3>
          <ul>
            <li>Diagnose: ascitic PMN <strong>&gt;250/μL</strong></li>
            <li>Tx: <strong>Cefotaxime or Ceftriaxone</strong> + albumin</li>
            <li>Albumin: <strong>1.5 g/kg</strong> day 1, <strong>1 g/kg</strong> day 3</li>
            <li>Prophylaxis: norfloxacin in high-risk patients</li>
          </ul>
        </div>
        <div class="card orange">
          <div class="top-bar"></div>
          <h3>🚨 Hepatorenal Syndrome (HRS)</h3>
          <ul>
            <li>Functional AKI — diagnosis of exclusion</li>
            <li>Stop diuretics + NSAIDs, rule out other causes</li>
            <li><strong>IV Albumin</strong> volume expansion</li>
            <li><strong>Terlipressin</strong> + albumin (vasoconstrictors)</li>
            <li>Definitive: <strong>liver transplantation</strong></li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- SLIDE 5 — VARICES -->
  <div class="slide" id="slide-5">
    <div class="tag">Slide 5 — Complication Management: Varices</div>
    <h2 style="margin-bottom:22px">Variceal Hemorrhage Protocols</h2>
    <div class="card-grid cols-3 content-wrap stagger">
      <div class="card blue">
        <div class="top-bar"></div>
        <h3>🛡️ Primary Prophylaxis<br><small style="font-weight:400;color:var(--sub);font-size:0.82rem">(Never bled)</small></h3>
        <ul>
          <li><strong>Carvedilol 3.125–12.5 mg/day</strong> — now preferred (vasodilating properties)</li>
          <li>Or propranolol / nadolol</li>
          <li>Alt if β-blocker contraindicated: <strong>EVL</strong> (endoscopic variceal ligation)</li>
          <li>EVL does NOT reduce portal pressure / prevent ascites</li>
        </ul>
        <p style="margin-top:10px; font-size:0.82rem"><strong>EGD Surveillance:</strong><br>No varices → q2-3yr<br>Small varices → q1-2yr</p>
      </div>
      <div class="card red">
        <div class="top-bar"></div>
        <h3>🚨 Acute Variceal Bleed<br><small style="font-weight:400;color:var(--sub);font-size:0.82rem">(Active hemorrhage)</small></h3>
        <ul>
          <li>ICU resuscitation — target <strong>Hb ~8 g/dL</strong> (avoid over-transfusion)</li>
          <li>Antibiotics: <strong>Ceftriaxone 1g/day × 5-7 days</strong> (↓ rebleeding + death)</li>
          <li>Vasoconstrictors: <strong>Octreotide</strong> 50 μg IV bolus → 50 μg/hr × 2-5 days</li>
          <li>Endoscopy: <strong>EVL</strong> (preferred)</li>
          <li>Failure → <strong>TIPS</strong></li>
        </ul>
      </div>
      <div class="card green">
        <div class="top-bar"></div>
        <h3>⚡ Early TIPS Strategy<br><small style="font-weight:400;color:var(--sub);font-size:0.82rem">(High-risk patients)</small></h3>
        <ul>
          <li>Preemptive TIPS within <strong>24–48 hours</strong></li>
          <li>Indicated for: Child C (score 10-13) or Child B with active bleeding at endoscopy</li>
          <li>Reduces failure rate + <strong>improves survival</strong></li>
          <li>Esophageal stent: bridge if bleeding continues</li>
        </ul>
        <p style="margin-top:10px; font-size:0.82rem"><strong>Secondary prophylaxis</strong> (after 1st bleed):<br>Non-selective β-blocker + EVL combination</p>
      </div>
    </div>
  </div>

  <!-- SLIDE 6 — ENCEPHALOPATHY -->
  <div class="slide" id="slide-6">
    <div class="tag">Slide 6 — Complication Management: Hepatic Encephalopathy</div>
    <h2 style="margin-bottom:22px">Hepatic Encephalopathy (HE)</h2>
    <div class="content-wrap stagger">
      <div class="card-grid cols-4" style="margin-bottom:18px">
        <div class="card yellow">
          <div class="top-bar"></div>
          <h3 style="font-size:0.9rem">Grade 1</h3>
          <p style="font-size:0.82rem">Inverted sleep-wake cycle, forgetfulness, distal tremor</p>
        </div>
        <div class="card yellow">
          <div class="top-bar"></div>
          <h3 style="font-size:0.9rem">Grade 2</h3>
          <p style="font-size:0.82rem">Confusion, bizarre behavior, disorientation</p>
        </div>
        <div class="card orange">
          <div class="top-bar"></div>
          <h3 style="font-size:0.9rem">Grade 3</h3>
          <p style="font-size:0.82rem">Lethargy, profound disorientation, <strong>asterixis</strong></p>
        </div>
        <div class="card red">
          <div class="top-bar"></div>
          <h3 style="font-size:0.9rem">Grade 4</h3>
          <p style="font-size:0.82rem"><strong>Coma</strong></p>
        </div>
      </div>

      <div class="card-grid cols-3">
        <div class="card blue">
          <div class="top-bar"></div>
          <h3>🔎 Identify Precipitants</h3>
          <ul>
            <li>GI bleeding</li>
            <li>Infection / sepsis</li>
            <li>Electrolyte disturbance</li>
            <li>Constipation</li>
            <li>Sedatives / opioids</li>
            <li>Renal failure</li>
            <li>Excess dietary protein</li>
          </ul>
        </div>
        <div class="card green">
          <div class="top-bar"></div>
          <h3>💊 First-Line: Lactulose</h3>
          <ul>
            <li><strong>15–45 mL PO bid-qid</strong> (or NG)</li>
            <li>Target: <strong>2-3 soft stools/day</strong></li>
            <li>↓ intestinal NH₃ absorption</li>
            <li>Minimal HE present in <strong>up to 80%</strong> of cirrhotics</li>
          </ul>
        </div>
        <div class="card purple">
          <div class="top-bar"></div>
          <h3>💊 Add-on: Rifaximin</h3>
          <ul>
            <li>Add when lactulose alone insufficient</li>
            <li>Rifaximin + lactulose <strong>superior</strong> to lactulose alone</li>
            <li>49.1% vs lactulose alone in clinical trials</li>
            <li>Use for chronic prevention</li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- SLIDE 7 — TRANSPLANT -->
  <div class="slide" id="slide-7">
    <div class="tag">Slide 7 — Definitive Treatment</div>
    <h2 style="margin-bottom:22px">Liver Transplantation & General Principles</h2>
    <div class="card-grid cols-2 content-wrap stagger">
      <div class="card red">
        <div class="top-bar"></div>
        <h3>🏥 Liver Transplant Indications</h3>
        <ul>
          <li>Decompensated cirrhosis — <strong>Child-Pugh B or C</strong></li>
          <li>MELD score <strong>≥15–17</strong></li>
          <li>HCC within <strong>Milan criteria</strong></li>
          <li>Hepatopulmonary syndrome</li>
          <li>Refractory variceal bleeding</li>
          <li>Recurrent/refractory ascites</li>
        </ul>
      </div>
      <div class="card blue">
        <div class="top-bar"></div>
        <h3>📋 General Management Principles</h3>
        <ul>
          <li><strong>Treat underlying etiology</strong> first (alcohol cessation, antivirals, metabolic control)</li>
          <li>Prevent decompensation with carvedilol</li>
          <li>Screen varices + HCC every 6 months</li>
          <li>Avoid nephrotoxins (NSAIDs, aminoglycosides)</li>
          <li>Vaccinate: Hep A, Hep B, pneumococcal, influenza</li>
          <li>Nutritional support — avoid protein restriction (except severe HE)</li>
        </ul>
      </div>
    </div>

    <div style="margin-top:18px; width:100%; max-width:1100px">
      <table class="data-table stagger">
        <thead>
          <tr>
            <th>Complication</th>
            <th>First-Line</th>
            <th>Second-Line / Add-on</th>
            <th>Definitive</th>
          </tr>
        </thead>
        <tbody>
          <tr><td><strong>Ascites</strong></td><td>Spironolactone + Na restriction</td><td>+ Furosemide; paracentesis + albumin</td><td>TIPS → Transplant</td></tr>
          <tr><td><strong>SBP</strong></td><td>Ceftriaxone + Albumin</td><td>Norfloxacin prophylaxis</td><td>Transplant</td></tr>
          <tr><td><strong>Variceal prophylaxis</strong></td><td>Carvedilol / propranolol</td><td>EVL if β-blocker contraindicated</td><td>—</td></tr>
          <tr><td><strong>Acute variceal bleed</strong></td><td>Octreotide + EVL + ceftriaxone</td><td>TIPS (esp. early for high-risk)</td><td>Transplant</td></tr>
          <tr><td><strong>Hepatic encephalopathy</strong></td><td>Lactulose + treat precipitants</td><td>Add Rifaximin</td><td>Transplant</td></tr>
          <tr><td><strong>Hepatorenal syndrome</strong></td><td>Albumin + Terlipressin</td><td>TIPS</td><td>Transplant</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <!-- SLIDE 8 — KEY TAKEAWAYS -->
  <div class="slide" id="slide-8">
    <div class="tag">Slide 8 — Key Takeaways</div>
    <h2 style="margin-bottom:24px">Remember These Pearls 🎓</h2>
    <div class="card-grid cols-3 content-wrap stagger">
      <div class="card red">
        <div class="top-bar"></div>
        <h3>📌 Staging is Everything</h3>
        <p>Compensated vs. decompensated drives ALL management decisions. <strong>Child-Pugh + MELD</strong> = your two scoring tools.</p>
      </div>
      <div class="card blue">
        <div class="top-bar"></div>
        <h3>📌 The 100:40 Rule</h3>
        <p>Spironolactone <strong>100 mg : Furosemide 40 mg</strong> for ascites — this ratio maintains potassium balance.</p>
      </div>
      <div class="card green">
        <div class="top-bar"></div>
        <h3>📌 Carvedilol is the New Standard</h3>
        <p>Non-selective β-blocker of choice for primary variceal prophylaxis — reduces decompensation and death.</p>
      </div>
      <div class="card orange">
        <div class="top-bar"></div>
        <h3>📌 Antibiotics Save Lives in Bleeds</h3>
        <p><strong>Ceftriaxone 1g/day</strong> during variceal hemorrhage reduces not just infections, but rebleeding and mortality.</p>
      </div>
      <div class="card yellow">
        <div class="top-bar"></div>
        <h3>📌 Hb Target = 8 g/dL</h3>
        <p>Over-transfusion in variceal bleed <strong>increases rebleeding</strong>. Don't chase normal hemoglobin.</p>
      </div>
      <div class="card purple">
        <div class="top-bar"></div>
        <h3>📌 Rifaximin + Lactulose Beats Lactulose Alone</h3>
        <p>For refractory hepatic encephalopathy — combination therapy is the current standard of care.</p>
      </div>
    </div>
    <p style="margin-top:24px; text-align:center; font-size:0.88rem; color:var(--sub)">Sources: Goldman-Cecil Medicine · Harrison's 22E · Robbins Pathology · Yamada's Gastroenterology · Washington Manual</p>
  </div>

</div><!-- /#deck -->

<!-- ═══════════════════════════════════════════════════
     CONTROLS
═══════════════════════════════════════════════════════ -->
<div id="controls">
  <button class="btn" id="prev-btn" title="Previous">‹</button>
  <button class="btn" id="play-btn" title="Play/Pause">▶</button>
  <button class="btn" id="next-btn" title="Next">›</button>
  <span id="slide-counter">1 / 9</span>
  <svg id="timer-svg" viewBox="0 0 38 38">
    <circle cx="19" cy="19" r="15" fill="none" stroke="var(--border)" stroke-width="3"/>
    <circle id="timer-circle" cx="19" cy="19" r="15"/>
  </svg>
</div>

<!-- ═══════════════════════════════════════════════════
     SCRIPT
═══════════════════════════════════════════════════════ -->
<script>
  const slides = document.querySelectorAll('.slide');
  const N = slides.length;
  const DURATION = 9000; // ms per slide

  let current = 0;
  let playing = false;
  let timer = null;
  let timerStart = null;
  let timerElapsed = 0;
  let rafId = null;

  const playBtn = document.getElementById('play-btn');
  const prevBtn = document.getElementById('prev-btn');
  const nextBtn = document.getElementById('next-btn');
  const counter = document.getElementById('slide-counter');
  const progressBar = document.getElementById('progress-bar');
  const timerCircle = document.getElementById('timer-circle');
  const circumference = 2 * Math.PI * 15; // r=15

  function updateUI() {
    counter.textContent = `${current + 1} / ${N}`;
    progressBar.style.width = `${((current) / (N - 1)) * 100}%`;
  }

  function goTo(idx, dir = 1) {
    const old = slides[current];
    old.classList.remove('active');
    old.classList.add('exit');
    setTimeout(() => old.classList.remove('exit'), 600);

    current = ((idx % N) + N) % N;
    slides[current].classList.add('active');
    updateUI();
    resetTimerRing();
  }

  function resetTimerRing() {
    timerElapsed = 0;
    timerStart = performance.now();
    timerCircle.style.transition = 'none';
    timerCircle.style.strokeDashoffset = circumference;
  }

  function tickRing(ts) {
    if (!playing) return;
    const elapsed = timerElapsed + (ts - timerStart);
    const frac = Math.min(elapsed / DURATION, 1);
    const offset = circumference * (1 - frac);
    timerCircle.style.transition = 'none';
    timerCircle.style.strokeDashoffset = offset;

    if (frac >= 1) {
      goTo(current + 1);
      timerStart = performance.now();
      timerElapsed = 0;
      // stop at last slide
      if (current === N - 1) {
        pause();
        return;
      }
    }
    rafId = requestAnimationFrame(tickRing);
  }

  function play() {
    playing = true;
    playBtn.textContent = '⏸';
    timerStart = performance.now();
    rafId = requestAnimationFrame(tickRing);
  }

  function pause() {
    playing = false;
    playBtn.textContent = '▶';
    if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
    timerElapsed += performance.now() - (timerStart || performance.now());
  }

  playBtn.addEventListener('click', () => { playing ? pause() : play(); });
  nextBtn.addEventListener('click', () => { pause(); goTo(current + 1); });
  prevBtn.addEventListener('click', () => { pause(); goTo(current - 1); });

  // keyboard navigation
  document.addEventListener('keydown', e => {
    if (e.key === 'ArrowRight' || e.key === ' ') { pause(); goTo(current + 1); }
    if (e.key === 'ArrowLeft') { pause(); goTo(current - 1); }
    if (e.key === 'p' || e.key === 'P') { playing ? pause() : play(); }
  });

  // init
  timerCircle.style.strokeDasharray = circumference;
  timerCircle.style.strokeDashoffset = circumference;
  updateUI();
</script>
</body>
</html>
Running Command

wc -l /home/daytona/workspace/cirrhosis-video/cirrhosis_management.html && echo "File size: $(du -sh /home/daytona/workspace/cirrhosis-video/cirrhosis_management.html | cut -f1)"

Your animated slideshow is ready! Download and open it in any browser:

cirrhosis management

HTML File · HTML


What's Inside (9 Slides)

SlideTopic
0Title — Liver Cirrhosis Management Protocols
1Definition, Pathogenesis & Causes
2Staging — Child-Pugh Table + MELD
3Diagnosis (clinical, labs, imaging)
4Ascites → SBP → HRS management
5Variceal hemorrhage protocols (primary prophylaxis, acute bleed, early TIPS)
6Hepatic encephalopathy grading + treatment
7Liver transplant indications + master summary table
86 Key Pearls to remember

How to Use

  • ▶ Play - auto-advances every 9 seconds (like a video)
  • ‹ › buttons or ← → keyboard arrows to navigate manually
  • Timer ring (bottom right of controls) shows time left on each slide
  • Fully self-contained HTML — works offline, no internet needed after download

Generate a printable one-page quick reference PDF on cirrhosis management

Reading File
Running Command

mkdir -p /home/daytona/workspace/cirrhosis-pdf && python3 -c "import reportlab; print('reportlab OK')" && python3 -c "from reportlab.lib.pagesizes import A4; print('A4 OK')"

Writing File

~/cirrhosis-pdf/build_pdf.py

"""
Cirrhosis Management – Printable One-Page Quick Reference
Generates a dense but readable A4 PDF using ReportLab
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm
from reportlab.platypus import (
    SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer,
    HRFlowable, KeepTogether
)
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.platypus.flowables import HRFlowable

# ── Colour palette ──────────────────────────────────────────────────────────
LIVER       = colors.HexColor("#b83232")   # header / accent
LIVER_LIGHT = colors.HexColor("#f9eaea")   # header bg rows
DARK        = colors.HexColor("#1a1a2e")   # title bar
BLUE_DARK   = colors.HexColor("#1e3a5f")   # section headers
BLUE_MID    = colors.HexColor("#e8f0fb")   # blue section bg
GREEN_DARK  = colors.HexColor("#1a4731")
GREEN_LIGHT = colors.HexColor("#e9f7ef")
ORANGE_DARK = colors.HexColor("#7d3a00")
ORANGE_LIGHT= colors.HexColor("#fff3e0")
PURPLE_DARK = colors.HexColor("#4a1c7c")
PURPLE_LIGHT= colors.HexColor("#f3eaff")
YELLOW_DARK = colors.HexColor("#5a4200")
YELLOW_LIGHT= colors.HexColor("#fffde7")
WHITE       = colors.white
GREY_LIGHT  = colors.HexColor("#f5f5f5")
GREY_MID    = colors.HexColor("#dddddd")
BLACK       = colors.black

W, H = A4   # 595 x 842 pt

# ── Page margins ────────────────────────────────────────────────────────────
MARGIN = 12 * mm

# ── Document ─────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    "/home/daytona/workspace/cirrhosis-pdf/cirrhosis_quick_reference.pdf",
    pagesize=A4,
    leftMargin=MARGIN, rightMargin=MARGIN,
    topMargin=MARGIN, bottomMargin=MARGIN,
)

# ── Styles ───────────────────────────────────────────────────────────────────
def S(name, **kw):
    return ParagraphStyle(name, **kw)

TITLE_S   = S("title",   fontSize=16, fontName="Helvetica-Bold", textColor=WHITE,        alignment=TA_CENTER, leading=20)
SUB_S     = S("sub",     fontSize=7.5, fontName="Helvetica",     textColor=colors.HexColor("#ccddff"), alignment=TA_CENTER, leading=10)
SEC_S     = S("sec",     fontSize=7.8, fontName="Helvetica-Bold", textColor=WHITE,       alignment=TA_CENTER, leading=10)
BODY_S    = S("body",    fontSize=6.8, fontName="Helvetica",      textColor=BLACK,       leading=9.5)
BOLD_S    = S("bold",    fontSize=6.8, fontName="Helvetica-Bold", textColor=BLACK,       leading=9.5)
SMALL_S   = S("small",   fontSize=6,   fontName="Helvetica",      textColor=colors.HexColor("#444444"), leading=8.5)
KEY_S     = S("key",     fontSize=6.8, fontName="Helvetica-Bold", textColor=LIVER,       leading=9.5)
CELL_H_S  = S("cellh",   fontSize=6.5, fontName="Helvetica-Bold", textColor=WHITE,       alignment=TA_CENTER, leading=9)
CELL_S    = S("cell",    fontSize=6.5, fontName="Helvetica",      textColor=BLACK,       leading=8.5)
CELL_B_S  = S("cellb",   fontSize=6.5, fontName="Helvetica-Bold", textColor=BLACK,       leading=8.5)
WARN_S    = S("warn",    fontSize=6.5, fontName="Helvetica-Bold", textColor=colors.HexColor("#7d0000"), leading=9)

def p(text, style=BODY_S): return Paragraph(text, style)
def pb(text): return Paragraph(text, BOLD_S)
def pk(text): return Paragraph(text, KEY_S)
def pc(text): return Paragraph(text, CELL_S)
def pcb(text): return Paragraph(text, CELL_B_S)
def pch(text): return Paragraph(text, CELL_H_S)
def ps(text): return Paragraph(text, SMALL_S)
def pw(text): return Paragraph(text, WARN_S)

def bullet(items, key_color=None):
    lines = []
    for item in items:
        if isinstance(item, tuple):
            key, val = item
            lines.append(Paragraph(f"<b>{key}</b> {val}", BODY_S))
        else:
            lines.append(Paragraph(f"• {item}", BODY_S))
    return lines

def section_header(text, bg=BLUE_DARK):
    data = [[pch(text)]]
    t = Table(data, colWidths=[W - 2*MARGIN])
    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), 4),
        ("RIGHTPADDING",  (0,0),(-1,-1), 4),
        ("ROUNDEDCORNERS", [2]),
    ]))
    return t

# ── Usable width ─────────────────────────────────────────────────────────────
UW = W - 2 * MARGIN   # ~171 mm

# ── Helper: colour box table ─────────────────────────────────────────────────
def colour_box(rows_data, col_widths, header_colors=None, row_colors=None, header_row=True):
    """rows_data: list of lists of Paragraph or string"""
    t = Table(rows_data, colWidths=col_widths)
    cmds = [
        ("TOPPADDING",    (0,0),(-1,-1), 2.5),
        ("BOTTOMPADDING", (0,0),(-1,-1), 2.5),
        ("LEFTPADDING",   (0,0),(-1,-1), 4),
        ("RIGHTPADDING",  (0,0),(-1,-1), 4),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
        ("GRID",          (0,0),(-1,-1), 0.3, GREY_MID),
    ]
    if header_row and header_colors:
        for i, col in enumerate(header_colors):
            if col:
                cmds.append(("BACKGROUND", (i,0),(i,0), col))
    if row_colors:
        for i, col in enumerate(row_colors):
            if col:
                cmds.append(("BACKGROUND", (0,i),(-1,i), col))
    t.setStyle(TableStyle(cmds))
    return t

# ══════════════════════════════════════════════════════════════════════════════
# BUILD STORY
# ══════════════════════════════════════════════════════════════════════════════
story = []

# ── TITLE BANNER ─────────────────────────────────────────────────────────────
title_data = [[
    p("🫀  LIVER CIRRHOSIS", TITLE_S),
    p("QUICK REFERENCE  |  Management Protocols", TITLE_S),
]]
title_t = Table(title_data, colWidths=[UW*0.42, UW*0.58])
title_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,-1), DARK),
    ("TOPPADDING",    (0,0),(-1,-1), 7),
    ("BOTTOMPADDING", (0,0),(-1,-1), 7),
    ("LEFTPADDING",   (0,0),(-1,-1), 8),
    ("RIGHTPADDING",  (0,0),(-1,-1), 8),
    ("VALIGN",        (0,0),(-1,-1), "MIDDLE"),
    ("ROUNDEDCORNERS", [3]),
]))
story.append(title_t)
story.append(Spacer(1, 2*mm))

# subtitle bar
sub_data = [[
    ps("Goldman-Cecil Medicine · Harrison's 22E · Robbins Pathology · Yamada's Gastroenterology · Washington Manual  |  July 2026")
]]
sub_t = Table(sub_data, colWidths=[UW])
sub_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(-1,-1), colors.HexColor("#f0f0f0")),
    ("TOPPADDING", (0,0),(-1,-1), 2), ("BOTTOMPADDING", (0,0),(-1,-1), 2),
    ("LEFTPADDING", (0,0),(-1,-1), 6), ("RIGHTPADDING", (0,0),(-1,-1), 6),
    ("ALIGN", (0,0),(-1,-1), "CENTER"),
]))
story.append(sub_t)
story.append(Spacer(1, 2.5*mm))

# ══════════════════════════════════════════════════════════════════════════════
# ROW 1:  Definition & Causes  |  Staging
# ══════════════════════════════════════════════════════════════════════════════
COL1 = UW * 0.34
COL2 = UW * 0.66

# ── LEFT: Definition + Causes ────────────────────────────────────────────────
def_rows = [
    [pch("DEFINITION & PATHOGENESIS")],
    [p("<b>Cirrhosis</b> = end-stage chronic liver disease — diffuse regenerative nodules surrounded by fibrous bands.")],
    [p("<b>Key cell:</b> Hepatic stellate cells (Ito cells) in space of Disse → activated → collagen I & III → portal HTN")],
    [p("<b>Reversible:</b> Fibrosis/cirrhosis can regress with disease treatment/remission")],
]
def_t = Table(def_rows, colWidths=[COL1 - 2])
def_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(0,0), BLUE_DARK),
    ("BACKGROUND", (0,1),(-1,-1), BLUE_MID),
    ("TOPPADDING",    (0,0),(-1,-1), 2.5), ("BOTTOMPADDING", (0,0),(-1,-1), 2.5),
    ("LEFTPADDING",   (0,0),(-1,-1), 4),   ("RIGHTPADDING",  (0,0),(-1,-1), 4),
    ("BOX",           (0,0),(-1,-1), 0.5,  BLUE_DARK),
    ("SPAN",          (0,0),(0,0)),
    ("ROWBACKGROUNDS",(0,1),(-1,-1),[BLUE_MID]),
]))

cause_rows = [
    [pch("AETIOLOGY"), pch("≈% WORLDWIDE")],
    [pc("Alcohol-related liver disease"), pc("30-35%")],
    [pc("NAFLD / MASLD"), pc("30-35%")],
    [pc("Chronic Hepatitis B"), pc("~25%")],
    [pc("Chronic Hepatitis C"), pc("~15%")],
    [pc("PBC / PSC / AIH"), pc("<5%")],
    [pc("Wilson's, Haemochromatosis, α1-AT"), pc("<2%")],
    [pc("Cryptogenic"), pc("~5%")],
]
cause_t = Table(cause_rows, colWidths=[COL1*0.66, COL1*0.34 - 2])
cause_t.setStyle(TableStyle([
    ("BACKGROUND",  (0,0),(-1,0), LIVER),
    ("ROWBACKGROUNDS",(0,1),(-1,-1), [WHITE, LIVER_LIGHT]),
    ("GRID",        (0,0),(-1,-1), 0.3, GREY_MID),
    ("TOPPADDING",    (0,0),(-1,-1), 2), ("BOTTOMPADDING", (0,0),(-1,-1), 2),
    ("LEFTPADDING",   (0,0),(-1,-1), 4), ("RIGHTPADDING",  (0,0),(-1,-1), 4),
    ("BOX",           (0,0),(-1,-1), 0.5, LIVER),
]))

left_col = Table([
    [def_t],
    [Spacer(1, 1.5*mm)],
    [cause_t],
], colWidths=[COL1 - 2])
left_col.setStyle(TableStyle([
    ("TOPPADDING", (0,0),(-1,-1), 0), ("BOTTOMPADDING", (0,0),(-1,-1), 0),
    ("LEFTPADDING", (0,0),(-1,-1), 0), ("RIGHTPADDING", (0,0),(-1,-1), 0),
]))

# ── RIGHT: STAGING ───────────────────────────────────────────────────────────
stage_rows = [
    [pch("STAGING"), pch("COMPENSATED"), pch("DECOMPENSATED")],
    [pcb("Definition"), pc("No complications"), pc("Ascites, variceal bleed, encephalopathy, or jaundice")],
    [pcb("Symptoms"), pc("~40% asymptomatic"), pc("Progressive symptoms")],
    [pcb("Child-Pugh"), pc("Class A (5-6 pts)"), pc("Class B (7-9) or C (≥10)")],
    [pcb("Action"), pc("Prevent decompensation; screen varices + HCC"), pc("Manage complications; evaluate TRANSPLANT")],
]
stage_t = Table(stage_rows, colWidths=[COL2*0.22, COL2*0.37, COL2*0.41 - 2])
stage_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,0), DARK),
    ("BACKGROUND",    (1,1),( 1,-1), colors.HexColor("#e8f5e9")),
    ("BACKGROUND",    (2,1),( 2,-1), colors.HexColor("#ffebee")),
    ("GRID",          (0,0),(-1,-1), 0.3, GREY_MID),
    ("BOX",           (0,0),(-1,-1), 0.5, DARK),
    ("TOPPADDING",    (0,0),(-1,-1), 2.5), ("BOTTOMPADDING", (0,0),(-1,-1), 2.5),
    ("LEFTPADDING",   (0,0),(-1,-1), 4),   ("RIGHTPADDING",  (0,0),(-1,-1), 4),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]))

# Child-Pugh table
cp_rows = [
    [pch("CHILD-PUGH"), pch("1 pt"), pch("2 pts"), pch("3 pts")],
    [pcb("Bilirubin"),      pc("<2"),        pc("2–3"),     pc(">3 mg/dL")],
    [pcb("Albumin"),        pc(">3.5"),      pc("2.8–3.5"), pc("<2.8 g/dL")],
    [pcb("PT/INR"),         pc("<1.7"),      pc("1.7–2.3"), pc(">2.3")],
    [pcb("Ascites"),        pc("None"),      pc("Mild"),    pc("Mod/severe")],
    [pcb("Encephalopathy"), pc("None"),      pc("Gr 1–2"),  pc("Gr 3–4")],
]
cw_cp = [COL2*0.28, COL2*0.24, COL2*0.24, COL2*0.24 - 2]
cp_t = Table(cp_rows, colWidths=cw_cp)
cp_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,0), BLUE_DARK),
    ("ROWBACKGROUNDS",(0,1),(-1,-1), [WHITE, BLUE_MID]),
    ("GRID",          (0,0),(-1,-1), 0.3, GREY_MID),
    ("BOX",           (0,0),(-1,-1), 0.5, BLUE_DARK),
    ("TOPPADDING",    (0,0),(-1,-1), 2), ("BOTTOMPADDING", (0,0),(-1,-1), 2),
    ("LEFTPADDING",   (0,0),(-1,-1), 4), ("RIGHTPADDING",  (0,0),(-1,-1), 4),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]))

meld_data = [[
    p("<b>MELD score</b> = 3.78×ln[bili] + 11.2×ln[INR] + 9.57×ln[Cr] + 6.43 &nbsp;|&nbsp; <b>≥15–17</b> → transplant listing threshold &nbsp;|&nbsp; More accurate than Child-Pugh for mortality prediction", SMALL_S)
]]
meld_t = Table(meld_data, colWidths=[COL2 - 2])
meld_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(-1,-1), colors.HexColor("#fff8e1")),
    ("BOX",        (0,0),(-1,-1), 0.5, colors.HexColor("#f0c000")),
    ("TOPPADDING", (0,0),(-1,-1), 2), ("BOTTOMPADDING", (0,0),(-1,-1), 2),
    ("LEFTPADDING", (0,0),(-1,-1), 5), ("RIGHTPADDING", (0,0),(-1,-1), 5),
]))

right_col = Table([
    [stage_t],
    [Spacer(1, 1.5*mm)],
    [cp_t],
    [Spacer(1, 1*mm)],
    [meld_t],
], colWidths=[COL2 - 2])
right_col.setStyle(TableStyle([
    ("TOPPADDING", (0,0),(-1,-1), 0), ("BOTTOMPADDING", (0,0),(-1,-1), 0),
    ("LEFTPADDING", (0,0),(-1,-1), 0), ("RIGHTPADDING", (0,0),(-1,-1), 0),
]))

row1 = Table([[left_col, right_col]], colWidths=[COL1, COL2])
row1.setStyle(TableStyle([
    ("TOPPADDING", (0,0),(-1,-1), 0), ("BOTTOMPADDING", (0,0),(-1,-1), 0),
    ("LEFTPADDING", (0,0),(-1,-1), 0), ("RIGHTPADDING", (0,0),(-1,-1), 3),
    ("VALIGN", (0,0),(-1,-1), "TOP"),
]))
story.append(row1)
story.append(Spacer(1, 2*mm))

# ══════════════════════════════════════════════════════════════════════════════
# ROW 2:  Complications – 4 panels
# ══════════════════════════════════════════════════════════════════════════════
PW4 = UW / 4  # each panel width

def make_panel(title, bg_header, bg_body, items, width=PW4):
    rows = [[pch(title)]]
    for item in items:
        if isinstance(item, str):
            rows.append([p(item)])
        elif isinstance(item, tuple) and len(item) == 2:
            rows.append([p(f"<b>{item[0]}</b> {item[1]}")])
        else:
            rows.append([item])
    t = Table(rows, colWidths=[width - 3])
    cmds = [
        ("BACKGROUND",    (0,0),(0,0), bg_header),
        ("BACKGROUND",    (0,1),(-1,-1), bg_body),
        ("BOX",           (0,0),(-1,-1), 0.5, bg_header),
        ("LINEBELOW",     (0,0),(0,0), 0.5, bg_header),
        ("TOPPADDING",    (0,0),(-1,-1), 2.5), ("BOTTOMPADDING", (0,0),(-1,-1), 2.5),
        ("LEFTPADDING",   (0,0),(-1,-1), 4),   ("RIGHTPADDING",  (0,0),(-1,-1), 4),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
    ]
    t.setStyle(TableStyle(cmds))
    return t

# ASCITES
ascites_items = [
    ("Step 1:", "Na restriction ≤2 g/day"),
    ("Step 2:", "<b>Spironolactone 100 mg</b> ± Furosemide 40 mg (100:40 ratio maintains K⁺)"),
    ("Refractory:", "Large-volume paracentesis + <b>albumin 8 g/L removed</b>"),
    ("Next:", "TIPS → Liver transplant"),
    "─────────────────────",
    pw("⚠ Avoid NSAIDs (precipitate HRS)"),
    pw("⚠ Stop diuretics if AKI/HRS"),
]
ascites_p = make_panel("ASCITES", BLUE_DARK, BLUE_MID, ascites_items, PW4)

# SBP + HRS
sbp_items = [
    p("<b>SPONTANEOUS BACTERIAL PERITONITIS</b>", BOLD_S),
    ("Dx:", "Ascitic PMN <b>&gt;250/μL</b> (even if asymptomatic)"),
    ("Tx:", "<b>Ceftriaxone 1g/day</b> IV + Albumin 1.5g/kg day-1, 1g/kg day-3"),
    ("Prophylaxis:", "Norfloxacin in high-risk pts"),
    p("<b>HEPATORENAL SYNDROME</b>", BOLD_S),
    ("Dx:", "Exclusion: stop diuretics, rule out hypovolaemia, nephrotoxins"),
    ("Tx:", "<b>IV Albumin + Terlipressin</b> (vasoconstrictors)"),
    ("Definitive:", "<b>Liver transplant</b>"),
]
sbp_p = make_panel("SBP & HRS", GREEN_DARK, GREEN_LIGHT, sbp_items, PW4)

# VARICES
varices_items = [
    p("<b>PRIMARY PROPHYLAXIS</b>", BOLD_S),
    ("Preferred:", "<b>Carvedilol 3.125–12.5 mg/day</b>"),
    ("Alt:", "Propranolol/nadolol; or EVL if β-blocker CI"),
    p("<b>ACUTE BLEED — ICU</b>", BOLD_S),
    ("Target Hb:", "<b>~8 g/dL</b> (avoid over-transfusion)"),
    ("Antibiotics:", "<b>Ceftriaxone 1g/day × 5–7 days</b>"),
    ("Vasoconstrictor:", "<b>Octreotide</b> 50μg IV → 50μg/hr"),
    ("Endoscopy:", "<b>EVL</b> (preferred)"),
    ("Failure:", "TIPS; Child C/B + active bleed → <b>early TIPS</b> within 24–48h"),
    p("<b>SECONDARY PROPHYLAXIS:</b> NSBB + EVL", BOLD_S),
]
varices_p = make_panel("VARICES", LIVER, LIVER_LIGHT, varices_items, PW4)

# ENCEPHALOPATHY
he_items = [
    p("<b>GRADES:</b> Gr1 sleep↓/forget → Gr2 confusion → Gr3 lethargy → Gr4 coma", BODY_S),
    ("Hallmark:", "<b>Asterixis</b>; fetor hepaticus; NH₃ unreliable"),
    p("<b>PRECIPITANTS — TREAT FIRST:</b>", BOLD_S),
    "GI bleed | Infection | Electrolytes | Constipation | Sedatives | Renal failure",
    p("<b>TREATMENT:</b>", BOLD_S),
    ("1st line:", "<b>Lactulose 15–45 mL bid-qid</b> → 2-3 stools/day"),
    ("Add-on:", "<b>Rifaximin</b> (combination > lactulose alone)"),
    ("Avoid:", "Unnecessary protein restriction"),
]
he_p = make_panel("HEPATIC ENCEPHALOPATHY", PURPLE_DARK, PURPLE_LIGHT, he_items, PW4)

comp_row = Table([[ascites_p, sbp_p, varices_p, he_p]], colWidths=[PW4, PW4, PW4, PW4])
comp_row.setStyle(TableStyle([
    ("TOPPADDING", (0,0),(-1,-1), 0), ("BOTTOMPADDING", (0,0),(-1,-1), 0),
    ("LEFTPADDING", (0,0),(-1,-1), 1), ("RIGHTPADDING", (0,0),(-1,-1), 1),
    ("VALIGN", (0,0),(-1,-1), "TOP"),
]))
story.append(comp_row)
story.append(Spacer(1, 2*mm))

# ══════════════════════════════════════════════════════════════════════════════
# ROW 3:  Master Drug Table  |  Key Clinical Pearls  |  Transplant/Surveillance
# ══════════════════════════════════════════════════════════════════════════════
CW_L = UW * 0.50
CW_M = UW * 0.27
CW_R = UW * 0.23

# ── MASTER DRUG TABLE ────────────────────────────────────────────────────────
drug_rows = [
    [pch("COMPLICATION"), pch("FIRST-LINE"), pch("SECOND-LINE / ADD-ON"), pch("DEFINITIVE")],
    [pc("Ascites"), pcb("Spironolactone 100mg + Na≤2g/d"), pc("+ Furosemide 40mg; LVP + Albumin 8g/L"), pc("TIPS → Transplant")],
    [pc("SBP"), pcb("Ceftriaxone 1g/d + Albumin 1.5→1g/kg"), pc("Long-term norfloxacin prophylaxis"), pc("Transplant")],
    [pc("1° Variceal Prophylaxis"), pcb("Carvedilol 3.125–12.5mg/d"), pc("Propranolol / nadolol; or EVL"), pc("—")],
    [pc("Acute Variceal Bleed"), pcb("Octreotide 50μg IV → 50μg/h + EVL"), pc("+ Ceftriaxone; TIPS if failure"), pc("Transplant")],
    [pc("Hepatic Encephalopathy"), pcb("Lactulose 15–45mL bid-qid"), pc("+ Rifaximin (superior combination)"), pc("Transplant")],
    [pc("Hepatorenal Syndrome"), pcb("IV Albumin + Terlipressin"), pc("TIPS in selected cases"), pc("Transplant")],
    [pc("HCC"), pcb("TACE / ablation / sorafenib"), pc("Resection if suitable"), pc("Transplant (Milan)")],
]
cw_drug = [CW_L*0.20, CW_L*0.31, CW_L*0.33, CW_L*0.16]
drug_t = Table(drug_rows, colWidths=cw_drug)
drug_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,0), DARK),
    ("ROWBACKGROUNDS",(0,1),(-1,-1), [WHITE, GREY_LIGHT]),
    ("GRID",          (0,0),(-1,-1), 0.3, GREY_MID),
    ("BOX",           (0,0),(-1,-1), 0.6, DARK),
    ("TOPPADDING",    (0,0),(-1,-1), 2.5), ("BOTTOMPADDING", (0,0),(-1,-1), 2.5),
    ("LEFTPADDING",   (0,0),(-1,-1), 3),   ("RIGHTPADDING",  (0,0),(-1,-1), 3),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
    ("FONTSIZE",      (0,0),(-1,-1), 6.2),
]))

# header label
drug_label = [[pch("MASTER DRUG QUICK REFERENCE")]]
drug_label_t = Table(drug_label, colWidths=[CW_L - 3])
drug_label_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(-1,-1), DARK),
    ("TOPPADDING", (0,0),(-1,-1), 2), ("BOTTOMPADDING", (0,0),(-1,-1), 2),
    ("LEFTPADDING", (0,0),(-1,-1), 4), ("RIGHTPADDING", (0,0),(-1,-1), 4),
]))
drug_wrap = Table([[drug_label_t],[drug_t]], colWidths=[CW_L - 3])
drug_wrap.setStyle(TableStyle([
    ("TOPPADDING",(0,0),(-1,-1),0),("BOTTOMPADDING",(0,0),(-1,-1),0),
    ("LEFTPADDING",(0,0),(-1,-1),0),("RIGHTPADDING",(0,0),(-1,-1),0),
]))

# ── KEY CLINICAL PEARLS ──────────────────────────────────────────────────────
pearl_items = [
    ("🔴", "Over-transfusion in variceal bleed → ↑rebleeding; target <b>Hb ~8 g/dL</b>"),
    ("🔵", "Child-Pugh B/C or MELD ≥15 → discuss <b>liver transplant NOW</b>"),
    ("🟢", "<b>100:40 rule</b>: spironolactone:furosemide = maintains K⁺ homeostasis"),
    ("🟡", "Carvedilol > propranolol/nadolol for portal pressure + decompensation prevention"),
    ("🟠", "SBP = PMN &gt;250/μL even WITHOUT symptoms — do diagnostic tap at every admission"),
    ("🔴", "<b>NH₃ level unreliable</b> for HE grading; &gt;150 μmol/L only supportive"),
    ("🔵", "EGD surveillance: no varices q2–3yr; small varices q1–2yr"),
    ("🟢", "Rifaximin + lactulose superior to lactulose alone (49% vs lactulose response)"),
    ("🟡", "After 1st variceal bleed → always <b>NSBB + EVL secondary prophylaxis</b>"),
    ("🟠", "Cryptogenic cirrhosis → consider NASH even if BMI normal (metabolic phenotype)"),
]
pearl_rows = [[pch("⚡ KEY CLINICAL PEARLS")]]
for em, txt in pearl_items:
    pearl_rows.append([p(f"{em}  {txt}")])

pearl_t = Table(pearl_rows, colWidths=[CW_M - 3])
pearl_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(0,0), colors.HexColor("#7d3a00")),
    ("BACKGROUND",    (0,1),(-1,-1), ORANGE_LIGHT),
    ("BOX",           (0,0),(-1,-1), 0.5, colors.HexColor("#7d3a00")),
    ("TOPPADDING",    (0,0),(-1,-1), 2.5), ("BOTTOMPADDING", (0,0),(-1,-1), 2.5),
    ("LEFTPADDING",   (0,0),(-1,-1), 4),   ("RIGHTPADDING",  (0,0),(-1,-1), 4),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]))

# ── TRANSPLANT + SURVEILLANCE ─────────────────────────────────────────────────
tx_items = [
    p("<b>TRANSPLANT INDICATIONS</b>", BOLD_S),
    "• Decompensated cirrhosis (Child B/C)",
    "• MELD ≥15–17",
    "• HCC within Milan criteria",
    "• Hepatopulmonary syndrome",
    "• Refractory ascites",
    "• Recurrent encephalopathy",
    Spacer(1, 1*mm),
    p("<b>SURVEILLANCE</b>", BOLD_S),
    "• HCC: US ± AFP q6 months",
    "• Varices EGD q1–3 yr",
    "• Bone density (DEXA)",
    Spacer(1, 1*mm),
    p("<b>VACCINATE</b>", BOLD_S),
    "• Hepatitis A + B",
    "• Pneumococcal",
    "• Influenza (annual)",
    Spacer(1, 1*mm),
    p("<b>GENERAL</b>", BOLD_S),
    "• Treat underlying cause",
    "• Nutritional support",
    "• Avoid nephrotoxins",
    "• No protein restriction",
    "  (except severe acute HE)",
]
tx_rows = [[pch("TRANSPLANT & SURVEILLANCE")]]
for item in tx_items:
    if isinstance(item, str):
        tx_rows.append([p(item)])
    else:
        tx_rows.append([item])

tx_t = Table(tx_rows, colWidths=[CW_R - 3])
tx_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(0,0), PURPLE_DARK),
    ("BACKGROUND",    (0,1),(-1,-1), PURPLE_LIGHT),
    ("BOX",           (0,0),(-1,-1), 0.5, PURPLE_DARK),
    ("TOPPADDING",    (0,0),(-1,-1), 2), ("BOTTOMPADDING", (0,0),(-1,-1), 2),
    ("LEFTPADDING",   (0,0),(-1,-1), 4), ("RIGHTPADDING",  (0,0),(-1,-1), 4),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]))

row3 = Table([[drug_wrap, pearl_t, tx_t]], colWidths=[CW_L, CW_M, CW_R])
row3.setStyle(TableStyle([
    ("TOPPADDING",  (0,0),(-1,-1), 0), ("BOTTOMPADDING", (0,0),(-1,-1), 0),
    ("LEFTPADDING", (0,0),(-1,-1), 1), ("RIGHTPADDING",  (0,0),(-1,-1), 1),
    ("VALIGN",      (0,0),(-1,-1), "TOP"),
]))
story.append(row3)
story.append(Spacer(1, 1.5*mm))

# ── FOOTER ────────────────────────────────────────────────────────────────────
footer_data = [[
    ps("FOR EDUCATIONAL USE ONLY — Always verify with current clinical guidelines. Not a substitute for clinical judgement."),
    ps("Orris Medical AI · Goldman-Cecil · Harrison's 22E · Robbins · Yamada · Washington Manual · July 2026"),
]]
footer_t = Table(footer_data, colWidths=[UW*0.55, UW*0.45])
footer_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(-1,-1), DARK),
    ("TOPPADDING",    (0,0),(-1,-1), 3), ("BOTTOMPADDING", (0,0),(-1,-1), 3),
    ("LEFTPADDING",   (0,0),(-1,-1), 6), ("RIGHTPADDING",  (0,0),(-1,-1), 6),
    ("ALIGN",         (0,0),(0,0), "LEFT"),
    ("ALIGN",         (1,0),(1,0), "RIGHT"),
    ("TEXTCOLOR",     (0,0),(-1,-1), colors.HexColor("#aaaaaa")),
]))
story.append(footer_t)

# ── BUILD ─────────────────────────────────────────────────────────────────────
doc.build(story)
print("PDF built successfully: cirrhosis_quick_reference.pdf")
Running Command

cd /home/daytona/workspace/cirrhosis-pdf && python3 build_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/cirrhosis-pdf/cirrhosis_quick_reference.pdf && python3 -c " from pypdf import PdfReader r = PdfReader('/home/daytona/workspace/cirrhosis-pdf/cirrhosis_quick_reference.pdf') print(f'Pages: {len(r.pages)}') print(f'Page size: {r.pages[0].mediabox}') "

Editing File

~/cirrhosis-pdf/build_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/cirrhosis-pdf/build_pdf.py'
Editing File

~/cirrhosis-pdf/build_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/cirrhosis-pdf/build_pdf.py'
Writing File

~/cirrhosis-pdf/build_pdf.py

"""
Cirrhosis Management – Printable One-Page Quick Reference
Single A4 page, dense layout, ReportLab
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer

# ── Colour palette ───────────────────────────────────────────────────────────
LIVER        = colors.HexColor("#b83232")
LIVER_LIGHT  = colors.HexColor("#fdecea")
DARK         = colors.HexColor("#1a1a2e")
BLUE_DARK    = colors.HexColor("#1e3a5f")
BLUE_MID     = colors.HexColor("#eaf2fb")
GREEN_DARK   = colors.HexColor("#1a4731")
GREEN_LIGHT  = colors.HexColor("#eaf7f0")
ORANGE_DARK  = colors.HexColor("#7d3a00")
ORANGE_LIGHT = colors.HexColor("#fff3e0")
PURPLE_DARK  = colors.HexColor("#4a1c7c")
PURPLE_LIGHT = colors.HexColor("#f3eaff")
WHITE        = colors.white
GREY_LIGHT   = colors.HexColor("#f5f5f5")
GREY_MID     = colors.HexColor("#dddddd")
BLACK        = colors.black

W, H   = A4
MARGIN = 10 * mm
UW     = W - 2 * MARGIN   # usable width ≈ 175 mm

# ── Document ─────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    "/home/daytona/workspace/cirrhosis-pdf/cirrhosis_quick_reference.pdf",
    pagesize=A4,
    leftMargin=MARGIN, rightMargin=MARGIN,
    topMargin=MARGIN,  bottomMargin=MARGIN,
)

# ── Style factory ────────────────────────────────────────────────────────────
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums  import TA_CENTER, TA_LEFT

def S(name, **kw): return ParagraphStyle(name, **kw)

T_S  = S("T",  fontSize=14,  fontName="Helvetica-Bold",  textColor=WHITE,   alignment=TA_CENTER, leading=17)
T2_S = S("T2", fontSize=8.5, fontName="Helvetica-Bold",  textColor=WHITE,   alignment=TA_CENTER, leading=12)
SH_S = S("SH", fontSize=6.0, fontName="Helvetica-Bold",  textColor=WHITE,   alignment=TA_CENTER, leading=8)
B_S  = S("B",  fontSize=6.0, fontName="Helvetica",       textColor=BLACK,   leading=8.0)
BB_S = S("BB", fontSize=6.0, fontName="Helvetica-Bold",  textColor=BLACK,   leading=8.0)
W_S  = S("W",  fontSize=5.8, fontName="Helvetica-Bold",  textColor=colors.HexColor("#7d0000"), leading=8)
SM_S = S("SM", fontSize=5.5, fontName="Helvetica",       textColor=colors.HexColor("#555555"), leading=7.5)
K_S  = S("K",  fontSize=5.8, fontName="Helvetica-Bold",  textColor=LIVER,   leading=8)

def p(t, sty=B_S):  return Paragraph(t, sty)
def pb(t):           return Paragraph(t, BB_S)
def ph(t):           return Paragraph(t, SH_S)
def ps(t):           return Paragraph(t, SM_S)

PAD = [
    ("TOPPADDING",    (0,0),(-1,-1), 1.8),
    ("BOTTOMPADDING", (0,0),(-1,-1), 1.8),
    ("LEFTPADDING",   (0,0),(-1,-1), 3.5),
    ("RIGHTPADDING",  (0,0),(-1,-1), 3.5),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]
SP = Spacer(1, 1.5*mm)

def tbl(data, cw, extra_cmds=None):
    t = Table(data, colWidths=cw)
    cmds = list(PAD) + (extra_cmds or [])
    t.setStyle(TableStyle(cmds))
    return t

def header_box(data, cw, hdr_bg=BLUE_DARK, row_bgs=None):
    """First row = coloured header, rest alternate."""
    extra = [
        ("BACKGROUND", (0,0),(-1,0), hdr_bg),
        ("BOX",        (0,0),(-1,-1), 0.4, hdr_bg),
        ("LINEBELOW",  (0,0),(-1,0),  0.4, hdr_bg),
        ("GRID",       (0,1),(-1,-1), 0.25, GREY_MID),
    ]
    if row_bgs:
        extra.append(("ROWBACKGROUNDS", (0,1),(-1,-1), row_bgs))
    return tbl(data, cw, extra)

story = []

# ════════════════════════════════════════════════════════════════════════════
# TITLE BAR
# ════════════════════════════════════════════════════════════════════════════
title_t = header_box(
    [[p("🫀  LIVER CIRRHOSIS", T_S),
      p("QUICK REFERENCE  |  Management Protocols", T2_S),
      p("Goldman-Cecil · Harrison's 22E · Robbins · Yamada · Washington Manual", SM_S)]],
    [UW*0.28, UW*0.42, UW*0.30],
    hdr_bg=DARK,
)
story.append(title_t)
story.append(SP)

# ════════════════════════════════════════════════════════════════════════════
# ROW 1 – Definition/Causes  |  Staging + Child-Pugh + MELD
# ════════════════════════════════════════════════════════════════════════════
C1 = UW * 0.33
C2 = UW * 0.67

# LEFT: definition + causes ─────────────────────────────────────────
def_t = header_box([
    [ph("DEFINITION & PATHOGENESIS")],
    [p("<b>Cirrhosis</b> = end-stage CLD; regenerative nodules + fibrous bands. Can partially <b>reverse</b> with treatment.")],
    [p("<b>Key cell:</b> Hepatic stellate cells (space of Disse) → activated on injury → collagen I/III → portal HTN")],
    [p("Leading causes: ALD · NAFLD/MASLD · Hep B · Hep C · PBC/PSC · Wilson's · Haemochromatosis · Cryptogenic")],
], [C1-2], hdr_bg=BLUE_DARK, row_bgs=[WHITE, BLUE_MID, WHITE])

cause_t = header_box([
    [ph("CAUSE"), ph("APPROX %")],
    [p("Alcohol-related liver disease"),   p("30–35%")],
    [p("NAFLD / MASLD"),                   p("30–35%")],
    [p("Chronic Hepatitis B"),             p("~25%")],
    [p("Chronic Hepatitis C"),             p("~15%")],
    [p("PBC/PSC/AIH/metabolic/other"),     p("<5%")],
], [C1*0.62, C1*0.38-2], hdr_bg=LIVER, row_bgs=[WHITE, LIVER_LIGHT, WHITE, LIVER_LIGHT, WHITE])

left_col_t = tbl([[def_t],[SP],[cause_t]], [C1-2])

# RIGHT: staging ────────────────────────────────────────────────────
stage_t = header_box([
    [ph(""), ph("COMPENSATED"), ph("DECOMPENSATED")],
    [pb("Definition"), p("No complications"), p("Ascites / variceal bleed / encephalopathy / jaundice")],
    [pb("~Symptoms"),  p("40% asymptomatic"),  p("Progressive; high mortality")],
    [pb("Child-Pugh"), p("Class A (5–6 pts)"), p("Class B (7–9) or C (≥10)")],
    [pb("Action"),     p("Prevent decompensation; screen varices + HCC q6m"),
                       p("Manage complications; <b>EVALUATE TRANSPLANT</b>")],
], [C2*0.18, C2*0.35, C2*0.47-2], hdr_bg=DARK, row_bgs=[WHITE, GREY_LIGHT, WHITE, GREY_LIGHT])

cp_t = header_box([
    [ph("CHILD-PUGH"), ph("1 pt"), ph("2 pts"), ph("3 pts"), ph("CLASS")],
    [pb("Bilirubin"),      p("<2"),     p("2–3"),     p(">3 mg/dL"),    p("A=5–6")],
    [pb("Albumin"),        p(">3.5"),   p("2.8–3.5"), p("<2.8 g/dL"),   p("B=7–9")],
    [pb("PT/INR"),         p("<1.7"),   p("1.7–2.3"), p(">2.3"),        p("C=≥10")],
    [pb("Ascites"),        p("None"),   p("Mild"),    p("Mod/severe"),  p("")],
    [pb("Encephalopathy"), p("None"),   p("Gr1–2"),   p("Gr3–4"),       p("")],
], [C2*0.23, C2*0.18, C2*0.18, C2*0.18, C2*0.23-2],
   hdr_bg=BLUE_DARK, row_bgs=[WHITE, BLUE_MID, WHITE, BLUE_MID, WHITE])

meld_t = tbl([[p(
    "<b>MELD</b> = 3.78·ln[bili] + 11.2·ln[INR] + 9.57·ln[Cr] + 6.43  |  "
    "MELD <b>≥15–17</b> → transplant listing  |  More accurate than Child-Pugh for survival"
)]], [C2-2], [("BACKGROUND",(0,0),(-1,-1),colors.HexColor("#fff8e1")),
              ("BOX",(0,0),(-1,-1),0.4,colors.HexColor("#e0a000"))])

right_col_t = tbl([[stage_t],[SP],[cp_t],[SP],[meld_t]], [C2-2])

row1 = tbl([[left_col_t, right_col_t]], [C1, C2])
story.append(row1)
story.append(SP)

# ════════════════════════════════════════════════════════════════════════════
# ROW 2 – 4 Complication Panels
# ════════════════════════════════════════════════════════════════════════════
P4 = UW / 4

def comp_panel(title, hdr_bg, body_bg, rows_data):
    data = [[ph(title)]] + [[p(r) if isinstance(r,str) else r] for r in rows_data]
    t = Table(data, colWidths=[P4-2.5])
    t.setStyle(TableStyle(PAD + [
        ("BACKGROUND", (0,0),(0,0), hdr_bg),
        ("BACKGROUND", (0,1),(-1,-1), body_bg),
        ("BOX",        (0,0),(-1,-1), 0.4, hdr_bg),
        ("LINEBELOW",  (0,0),(0,0),   0.4, hdr_bg),
    ]))
    return t

ascites_p = comp_panel("ASCITES", BLUE_DARK, BLUE_MID, [
    "<b>Step 1:</b> Na restriction ≤2 g/day",
    "<b>Step 2:</b> Spironolactone 100 mg ± Furosemide 40 mg (100:40 ratio maintains K⁺)",
    "<b>Refractory:</b> Large-volume paracentesis + <b>albumin 8 g/L removed</b>",
    "<b>Next:</b> TIPS → Liver transplant",
    p("⚠ Avoid NSAIDs — precipitate HRS", W_S),
    p("⚠ Stop diuretics if AKI develops", W_S),
])

sbp_p = comp_panel("SBP & HEPATORENAL SYNDROME", GREEN_DARK, GREEN_LIGHT, [
    pb("SPONTANEOUS BACTERIAL PERITONITIS"),
    "<b>Dx:</b> Ascitic PMN <b>&gt;250/μL</b> (tap every admission)",
    "<b>Tx:</b> Ceftriaxone 1g/d IV + Albumin 1.5g/kg d1, 1g/kg d3",
    "<b>Prophylaxis:</b> Norfloxacin in high-risk pts",
    pb("HEPATORENAL SYNDROME"),
    "<b>Dx:</b> Exclusion — stop diuretics, check volume, rule out nephrotoxins",
    "<b>Tx:</b> IV Albumin + <b>Terlipressin</b> (vasoconstrictors)",
    "<b>Definitive:</b> Liver transplant",
])

varices_p = comp_panel("VARICES", LIVER, LIVER_LIGHT, [
    pb("PRIMARY PROPHYLAXIS (never bled)"),
    "<b>Preferred:</b> Carvedilol 3.125–12.5 mg/day",
    "<b>Alt:</b> Propranolol/nadolol; EVL if β-blocker CI",
    pb("ACUTE VARICEAL BLEED — ICU"),
    "<b>Hb target ~8 g/dL</b> (over-transfusion ↑ rebleed)",
    "<b>Antibiotics:</b> Ceftriaxone 1g/d × 5–7 days",
    "<b>Vasoconstrictor:</b> Octreotide 50μg IV → 50μg/hr",
    "<b>Endoscopy:</b> EVL (preferred)",
    "<b>Failure:</b> TIPS; Child C/B+active bleed → early TIPS 24–48h",
    pb("2° PROPHYLAXIS: NSBB + EVL"),
])

he_p = comp_panel("HEPATIC ENCEPHALOPATHY", PURPLE_DARK, PURPLE_LIGHT, [
    "<b>Gr1</b> Sleep inversion/forget → <b>Gr2</b> Confusion → <b>Gr3</b> Lethargy → <b>Gr4</b> Coma",
    "<b>Hallmark:</b> Asterixis; fetor hepaticus; NH₃ unreliable (&gt;150 supportive)",
    pb("PRECIPITANTS (treat first):"),
    "GI bleed · Infection · Electrolytes · Constipation · Sedatives · AKI",
    pb("TREATMENT:"),
    "<b>1st:</b> Lactulose 15–45 mL bid-qid → 2–3 stools/day",
    "<b>Add:</b> Rifaximin (combination superior to lactulose alone)",
    "Avoid unnecessary protein restriction",
])

row2 = tbl([[ascites_p, sbp_p, varices_p, he_p]], [P4,P4,P4,P4])
story.append(row2)
story.append(SP)

# ════════════════════════════════════════════════════════════════════════════
# ROW 3 – Master Drug Table | Pearls | Transplant
# ════════════════════════════════════════════════════════════════════════════
DW = UW * 0.50
PW = UW * 0.27
TW = UW * 0.23

# Drug table ─────────────────────────────────────────────────────────
drug_t = header_box([
    [ph("COMPLICATION"), ph("FIRST-LINE"), ph("SECOND-LINE / ADD-ON"), ph("DEFINITIVE")],
    [p("Ascites"),                 pb("Spironolactone 100mg + Na≤2g/d"),      p("Furosemide 40mg; LVP+albumin 8g/L"),   p("TIPS → Tx")],
    [p("SBP"),                     pb("Ceftriaxone 1g/d + Albumin"),           p("1.5g/kg d1, 1g/kg d3; norfloxacin Px"), p("Transplant")],
    [p("1° Variceal Prophylaxis"), pb("Carvedilol 3.125–12.5mg/d"),            p("Propranolol/nadolol; EVL if CI"),        p("—")],
    [p("Acute Variceal Bleed"),    pb("Octreotide 50μg→50μg/h + EVL"),         p("Ceftriaxone 1g/d; TIPS if failure"),     p("Transplant")],
    [p("Hepatic Encephalopathy"),  pb("Lactulose 15–45mL bid-qid"),            p("+ Rifaximin (combination preferred)"),   p("Transplant")],
    [p("Hepatorenal Syndrome"),    pb("IV Albumin + Terlipressin"),             p("TIPS in selected cases"),                p("Transplant")],
    [p("HCC"),                     pb("TACE / ablation / sorafenib"),          p("Resection if localised"),                p("Tx (Milan)")],
], [DW*0.21, DW*0.32, DW*0.33, DW*0.14],
   hdr_bg=DARK, row_bgs=[WHITE, GREY_LIGHT, WHITE, GREY_LIGHT, WHITE, GREY_LIGHT, WHITE])

drug_label_t = tbl([[ph("MASTER DRUG QUICK REFERENCE")]], [DW-2],
    [("BACKGROUND",(0,0),(-1,-1),DARK),("BOX",(0,0),(-1,-1),0.4,DARK)])
drug_wrap = tbl([[drug_label_t],[drug_t]], [DW-2])

# Pearls ────────────────────────────────────────────────────────────
pearl_rows = [
    [ph("⚡ KEY CLINICAL PEARLS")],
    [p("🔴 <b>Hb target ~8 g/dL</b> in acute variceal bleed — over-transfusion ↑ rebleeding")],
    [p("🔵 Child-Pugh B/C or MELD ≥15 → refer for <b>liver transplant evaluation NOW</b>")],
    [p("🟢 <b>100:40 rule</b>: spironolactone:furosemide maintains potassium homeostasis")],
    [p("🟡 Carvedilol > propranolol for portal HTN reduction + decompensation prevention")],
    [p("🟠 <b>SBP = PMN >250/μL even without symptoms</b> — diagnostic tap at every admission")],
    [p("🔴 NH₃ unreliable for HE grading; >150 μmol/L only supportive evidence")],
    [p("🔵 EGD surveillance: no varices q2–3yr; small varices q1–2yr; decompensated sooner")],
    [p("🟢 Rifaximin + lactulose combination <b>superior</b> to lactulose alone for HE")],
    [p("🟡 After 1st variceal bleed → always <b>NSBB + EVL secondary prophylaxis</b>")],
    [p("🟠 <b>Early TIPS within 24–48h</b>: indicated for Child C (10–13) or Child B + active bleed")],
]
pearl_t = Table(pearl_rows, colWidths=[PW-2])
pearl_t.setStyle(TableStyle(PAD + [
    ("BACKGROUND", (0,0),(0,0), ORANGE_DARK),
    ("BACKGROUND", (0,1),(-1,-1), ORANGE_LIGHT),
    ("BOX",        (0,0),(-1,-1), 0.4, ORANGE_DARK),
]))

# Transplant/Surveillance ──────────────────────────────────────────
tx_rows = [
    [ph("TRANSPLANT & SURVEILLANCE")],
    [pb("TRANSPLANT INDICATIONS:")],
    [p("• Decompensated (Child B/C) or MELD ≥15–17")],
    [p("• HCC within Milan criteria")],
    [p("• Hepatopulmonary syndrome")],
    [p("• Refractory ascites / recurrent HE")],
    [pb("SURVEILLANCE:")],
    [p("• HCC: US ± AFP every 6 months")],
    [p("• Varices: EGD q1–3 years")],
    [p("• DEXA (osteoporosis screening)")],
    [pb("VACCINATE:")],
    [p("• Hep A, Hep B, Pneumococcal, Influenza")],
    [pb("GENERAL PRINCIPLES:")],
    [p("• Treat underlying aetiology")],
    [p("• Avoid NSAIDs, aminoglycosides")],
    [p("• Nutritional support; no protein restriction (except severe acute HE)")],
]
tx_t = Table(tx_rows, colWidths=[TW-2])
tx_t.setStyle(TableStyle(PAD + [
    ("BACKGROUND", (0,0),(0,0), PURPLE_DARK),
    ("BACKGROUND", (0,1),(-1,-1), PURPLE_LIGHT),
    ("BOX",        (0,0),(-1,-1), 0.4, PURPLE_DARK),
]))

row3 = tbl([[drug_wrap, pearl_t, tx_t]], [DW, PW, TW])
story.append(row3)
story.append(SP)

# ════════════════════════════════════════════════════════════════════════════
# FOOTER
# ════════════════════════════════════════════════════════════════════════════
footer_t = tbl([[
    ps("FOR EDUCATIONAL USE ONLY — Always verify with current clinical guidelines. Not a substitute for clinical judgement."),
    ps("Orris Medical AI · Goldman-Cecil · Harrison's 22E · Robbins · Yamada · Washington Manual · July 2026"),
]], [UW*0.52, UW*0.48], [
    ("BACKGROUND",(0,0),(-1,-1), DARK),
    ("TEXTCOLOR",  (0,0),(-1,-1), colors.HexColor("#aaaaaa")),
    ("ALIGN",      (1,0),(1,0), "RIGHT"),
])
story.append(footer_t)

# ── Build ──────────────────────────────────────────────────────────────────
doc.build(story)
print("PDF built successfully.")
Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.