Liver anatomy

Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Loading Image
Reading File
Reading File
Loading Image
Reading File
Loading Image
Reading File
Loading Image
I have comprehensive content and four excellent diagrams. I can now compose a thorough, well-illustrated answer.

Liver Anatomy

Overview

The liver is the largest solid organ (and largest gland) in the body, weighing approximately 1,500 g. It sits in the right upper quadrant beneath the diaphragm, protected by the lower rib cage. It is reddish-brown and encased by a fibrous sheath called Glisson's capsule, which extends inward along the portal tracts. - Schwartz's Principles of Surgery, 11th Ed.

Ligaments and Peritoneal Reflections

The liver is anchored in place by several ligaments:
Liver ligaments - anterior view showing falciform, round, and triangular ligaments
LigamentDescription
Falciform ligamentSeparates the left lateral from the left medial segment (umbilical fissure); anchors the liver to the anterior abdominal wall. The falciform does NOT divide right from left lobe
Round ligament (ligamentum teres)Obliterated umbilical vein; runs from the umbilicus to the left liver hilum at the front edge of the falciform ligament
Ligamentum venosum (Arantius' ligament)Obliterated ductus venosus; lies deep between the caudate lobe and the left lateral segment
Coronary ligamentsExtend anteriorly from the triangular ligaments; the right coronary ligament anchors the liver to the right retroperitoneum/kidney
Left & right triangular ligamentsSecure both sides of the liver to the diaphragm
Hepatoduodenal ligament (porta hepatis)Contains the common bile duct, hepatic artery, and portal vein
Gastrohepatic ligamentConnects the liver to the lesser curvature of the stomach (lesser omentum)
The foramen of Winslow (epiploic foramen) lies posterior to the porta hepatis and connects to the lesser sac - this is the site of the Pringle maneuver (clamping the hepatoduodenal ligament to control inflow). - Bailey & Love's Short Practice of Surgery, 28th Ed.

Lobar Anatomy

The liver is divided into right and left lobes by Cantlie's line - an imaginary plane from the gallbladder fossa to the inferior vena cava (IVC). The middle hepatic vein runs within this plane.
  • Right lobe: 60-70% of liver mass
  • Left lobe + caudate lobe: remaining 30-40%
  • The caudate lobe (segment I) sits anterior and left of the IVC, containing three sub-segments: the Spiegel lobe, the paracaval portion, and the caudate process
Note: The falciform ligament is NOT the true left-right boundary - it separates the left lateral segment (II, III) from the left medial segment (IV). - Sabiston Textbook of Surgery

Couinaud's Segmental Anatomy

Couinaud, a French anatomist working in the early 1950s, divided the liver into 8 functionally independent segments, numbered clockwise starting from the caudate lobe:
Couinaud's liver segments - anterior and inferior views
Couinaud segments with portal vein distribution - exploded view
SegmentLocationLobe
ICaudate lobe (posterior, adjacent to IVC)Caudate
IIPosterior left lateralLeft lateral
IIIAnterior left lateralLeft lateral
IV (IVa/IVb)Left medial (IVa = cephalad, IVb = caudal)Left medial
VInferior right anteriorRight lobe
VIInferior right posteriorRight lobe
VIISuperior right posteriorRight lobe
VIIISuperior right anteriorRight lobe
Each segment has its own independent branch of the portal vein, hepatic artery, and bile duct - plus venous drainage via a hepatic vein tributary. This makes segment-specific ("anatomical") resections possible. - Gray's Anatomy for Students; Schwartz's Principles of Surgery
Surgical relevance: A right hepatectomy removes segments V-VIII; a left hepatectomy removes segments I-IV. The caudate lobe (segment I) has unique direct venous drainage into the IVC.

Blood Supply

Dual Blood Supply

The liver has a unique dual blood supply:
  • Portal vein: ~80% of total blood flow (nutrient-rich blood from the gut, spleen, and pancreas)
  • Hepatic artery: ~20% of blood flow (oxygenated blood)

Arterial Supply

Hepatic arterial anatomy and hilum
The arterial supply arises from the coeliac trunk, which divides into the left gastric, common hepatic, and splenic arteries. The common hepatic artery gives off the gastroduodenal artery, then continues as the hepatic artery proper, which bifurcates into right and left hepatic arteries at the hilum.
Important variants (clinically significant before surgery):
  • A replaced/accessory right hepatic artery may arise from the superior mesenteric artery (SMA), running posterior to the bile duct
  • A replaced/accessory left hepatic artery may arise from the left gastric artery, running in the lesser omentum

Portal Vein

The portal vein is formed by the confluence of the splenic vein and superior mesenteric vein behind the neck of the pancreas. It enters the hilum and divides into right and left branches. The left branch has a longer (~2 cm) extrahepatic course.

Venous Drainage

Three major hepatic veins drain into the IVC just below the diaphragm:
  • Right hepatic vein (drains segments VI and VII) - can be exposed fully outside the parenchyma
  • Middle hepatic vein (drains segments IV, V, and VIII) - runs in Cantlie's line
  • Left hepatic vein (drains segments II and III)
The middle and left hepatic veins usually join a short common trunk before entering the IVC. The retrohepatic IVC occupies a deep groove on the posterior surface of the liver. - Bailey & Love's, 28th Ed.

The Porta Hepatis (Hilum)

The porta hepatis is a transverse fissure on the visceral surface. The contents of the hepatoduodenal ligament, from anterior to posterior (in the classic arrangement), are:
  • Bile duct - right free edge (anterior)
  • Hepatic artery proper - medially
  • Portal vein - posteriorly
The right and left hepatic ducts emerge from the parenchyma and unite to form the common hepatic duct, which then receives the cystic duct (from the gallbladder) to become the common bile duct (CBD).

Microscopic Anatomy

The liver contains ~100,000 hexagonal lobules, each organized around a central vein and surrounded by six portal triads (each containing a branch of the portal vein, hepatic artery, and bile duct).
Blood flows from the portal triads → through sinusoids (large-diameter, fenestrated capillaries) → to the central vein. Key cell types:
Cell TypeFunction
HepatocytesMetabolism, glycolysis/gluconeogenesis, protein synthesis, bile production, detoxification
Kupffer cellsSinusoidal macrophages; phagocytose effete RBCs and foreign antigens
Endothelial cellsLine the sinusoids; highly fenestrated for exchange
Stellate cells (Ito cells)Fat storage (vitamin A); activated to myofibroblasts in fibrosis
Bile canaliculi run parallel to sinusoids on the opposite side of the hepatocyte - bile drains in the opposite direction to blood flow, toward the portal tracts. - Bailey & Love's, 28th Ed.

Embryology

Liver development begins at 3-4 weeks' gestation when a hepatic foregut diverticulum buds from the ventral wall of the primitive midgut into the septum transversum. Bipotential hepatoblasts then differentiate into hepatocytes and cholangiocytes. The same diverticulum gives rise to the extrahepatic bile ducts, gallbladder, and ventral pancreas. - Bailey & Love's, 28th Ed.

Key Surgical Points

  • The liver is the only organ that fully regenerates (90-100% of its previous volume after resection)
  • Inflow control (Pringle maneuver) is achieved by clamping the hepatoduodenal ligament at the foramen of Winslow
  • All liver ligaments (falciform, triangular, coronary) can be divided in a bloodless plane for full mobilization
  • Segment I (caudate) has direct independent venous drainage to the IVC, making it anatomically distinct

Make a pdf of everything you told

Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null || echo "workspace empty or does not exi…

Running Command

mkdir -p /home/daytona/workspace/liver-anatomy && python3 -c "from reportlab.lib…

Writing File

~/liver-anatomy/build_pdf.py

import requests
import os
from io import BytesIO
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    Image, HRFlowable, PageBreak, KeepTogether
)
from reportlab.platypus.tableofcontents import TableOfContents

OUTPUT = "/home/daytona/workspace/liver-anatomy/Liver_Anatomy.pdf"

# ── colour palette ──────────────────────────────────────────────────────────
DARK_RED   = colors.HexColor("#8B1A1A")
MID_RED    = colors.HexColor("#C0392B")
LIGHT_GREY = colors.HexColor("#F5F5F5")
MID_GREY   = colors.HexColor("#CCCCCC")
DARK_GREY  = colors.HexColor("#444444")
WHITE      = colors.white

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

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

title_style = make_style('DocTitle',
    fontSize=28, textColor=WHITE, alignment=TA_CENTER,
    spaceAfter=6, fontName='Helvetica-Bold')

subtitle_style = make_style('DocSubtitle',
    fontSize=13, textColor=colors.HexColor("#FFCCCC"),
    alignment=TA_CENTER, spaceAfter=4, fontName='Helvetica')

h1_style = make_style('H1',
    fontSize=16, textColor=WHITE, fontName='Helvetica-Bold',
    spaceBefore=18, spaceAfter=6, leftIndent=0)

h2_style = make_style('H2',
    fontSize=13, textColor=DARK_RED, fontName='Helvetica-Bold',
    spaceBefore=14, spaceAfter=4)

body_style = make_style('Body',
    fontSize=10, textColor=DARK_GREY, fontName='Helvetica',
    leading=15, spaceAfter=6, alignment=TA_JUSTIFY)

bullet_style = make_style('Bullet',
    fontSize=10, textColor=DARK_GREY, fontName='Helvetica',
    leading=14, spaceAfter=3, leftIndent=16, firstLineIndent=-10)

note_style = make_style('Note',
    fontSize=9, textColor=colors.HexColor("#555555"),
    fontName='Helvetica-Oblique', leftIndent=12, spaceAfter=4,
    borderPad=4, backColor=colors.HexColor("#FFF8E7"),
    borderColor=colors.HexColor("#E8C87A"), borderWidth=0.5)

caption_style = make_style('Caption',
    fontSize=8.5, textColor=colors.HexColor("#666666"),
    fontName='Helvetica-Oblique', alignment=TA_CENTER, spaceAfter=8)

source_style = make_style('Source',
    fontSize=8, textColor=colors.HexColor("#888888"),
    fontName='Helvetica-Oblique', alignment=TA_CENTER, spaceAfter=2)

# ── helpers ──────────────────────────────────────────────────────────────────
def download_image(url, max_w_cm, max_h_cm):
    """Download image URL and return a ReportLab Image flowable."""
    try:
        r = requests.get(url, timeout=15)
        r.raise_for_status()
        img_data = BytesIO(r.content)
        img = Image(img_data)
        w = img.imageWidth
        h = img.imageHeight
        ratio = h / w
        target_w = max_w_cm * cm
        target_h = target_w * ratio
        if target_h > max_h_cm * cm:
            target_h = max_h_cm * cm
            target_w = target_h / ratio
        img.drawWidth  = target_w
        img.drawHeight = target_h
        return img
    except Exception as e:
        print(f"  WARNING: could not download {url}: {e}")
        return None

def h1_block(text):
    """Section heading with coloured background bar."""
    tbl = Table([[Paragraph(text, h1_style)]], colWidths=[17*cm])
    tbl.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), DARK_RED),
        ('TOPPADDING',    (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('LEFTPADDING',   (0,0), (-1,-1), 12),
        ('RIGHTPADDING',  (0,0), (-1,-1), 12),
        ('ROUNDEDCORNERS', [4, 4, 4, 4]),
    ]))
    return tbl

def section_table(rows, col_widths=None):
    """Zebra-striped table."""
    if col_widths is None:
        col_widths = [17*cm / len(rows[0])] * len(rows[0])
    tbl = Table(rows, colWidths=col_widths, repeatRows=1)
    style = [
        ('BACKGROUND',    (0,0), (-1,0),  DARK_RED),
        ('TEXTCOLOR',     (0,0), (-1,0),  WHITE),
        ('FONTNAME',      (0,0), (-1,0),  'Helvetica-Bold'),
        ('FONTSIZE',      (0,0), (-1,-1), 9),
        ('GRID',          (0,0), (-1,-1), 0.4, MID_GREY),
        ('ROWBACKGROUNDS',(0,1), (-1,-1), [WHITE, LIGHT_GREY]),
        ('VALIGN',        (0,0), (-1,-1), 'TOP'),
        ('TOPPADDING',    (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING',   (0,0), (-1,-1), 6),
        ('RIGHTPADDING',  (0,0), (-1,-1), 6),
    ]
    tbl.setStyle(TableStyle(style))
    return tbl

def key_point_box(items):
    """A coloured callout box for key points."""
    content = "<br/>".join(f"&#x25BA; {i}" for i in items)
    p = Paragraph(content, make_style('KP', fontSize=9.5,
        textColor=DARK_GREY, fontName='Helvetica',
        leading=15, leftIndent=6))
    tbl = Table([[p]], colWidths=[17*cm])
    tbl.setStyle(TableStyle([
        ('BACKGROUND',    (0,0), (-1,-1), colors.HexColor("#FFF0F0")),
        ('LEFTPADDING',   (0,0), (-1,-1), 10),
        ('RIGHTPADDING',  (0,0), (-1,-1), 10),
        ('TOPPADDING',    (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('BOX',           (0,0), (-1,-1), 1, DARK_RED),
    ]))
    return tbl

# ── IMAGE URLS ────────────────────────────────────────────────────────────────
IMG_LIGAMENTS = "https://cdn.orris.care/cdss_images/40a4df60070121ed63b336390c6f63fce64bca6d660ed7304cf7436393e3d139.png"
IMG_COUINAUD  = "https://cdn.orris.care/cdss_images/2fd77fece5101e13c490d3fa0610fb8b45be31c0e4efd56b213e0167855d43a8.png"
IMG_SEGMENTS2 = "https://cdn.orris.care/cdss_images/2b37cf1bc313c931a0488bf6ad462abfe51dcf0af34dd1ca4a5ac5d96dc047be.png"
IMG_HILUM     = "https://cdn.orris.care/cdss_images/19fab108bcf7c5dca1b2c715d5b676266e5bde8853fbecaf8bb9b53817c0af2e.png"

# ── BUILD ─────────────────────────────────────────────────────────────────────
def build():
    doc = SimpleDocTemplate(
        OUTPUT,
        pagesize=A4,
        leftMargin=2.2*cm, rightMargin=2.2*cm,
        topMargin=2.0*cm,  bottomMargin=2.0*cm,
        title="Liver Anatomy",
        author="Orris Medical Reference",
    )

    story = []

    # ═══════════════════ COVER BLOCK ════════════════════════════════════════
    cover_text = Table(
        [[Paragraph("LIVER ANATOMY", title_style)],
         [Paragraph("Comprehensive Reference — Gross, Segmental, Vascular & Microscopic", subtitle_style)],
         [Spacer(1, 0.3*cm)],
         [Paragraph("Sources: Schwartz's Principles of Surgery · Bailey & Love's Surgery · Gray's Anatomy for Students · Sabiston Textbook of Surgery", source_style)],
        ],
        colWidths=[17*cm]
    )
    cover_text.setStyle(TableStyle([
        ('BACKGROUND',    (0,0), (-1,-1), DARK_RED),
        ('TOPPADDING',    (0,0), (-1,-1), 18),
        ('BOTTOMPADDING', (0,0), (-1,-1), 18),
        ('LEFTPADDING',   (0,0), (-1,-1), 16),
        ('RIGHTPADDING',  (0,0), (-1,-1), 16),
    ]))
    story.append(cover_text)
    story.append(Spacer(1, 0.7*cm))

    # ═══════════════════ 1. OVERVIEW ════════════════════════════════════════
    story.append(h1_block("1. Overview"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "The liver is the largest solid organ (and largest gland) in the body, weighing approximately "
        "<b>1,500 g</b>. It sits in the <b>right upper quadrant</b> beneath the diaphragm, protected by the "
        "lower rib cage. It is reddish-brown and encased by a fibrous sheath called <b>Glisson's capsule</b>, "
        "which extends inward along the portal tracts into the liver parenchyma.",
        body_style))
    story.append(Spacer(1, 0.2*cm))
    story.append(key_point_box([
        "Two anatomical lobes, each with separate blood supply, bile duct, and venous drainage",
        "Dual blood supply: 80% portal vein + 20% hepatic artery",
        "Only organ in the body capable of full regeneration (90–100% of previous volume after resection)",
        "Resection is planned along anatomical lines to preserve maximal functioning parenchyma",
    ]))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 2. EMBRYOLOGY ══════════════════════════════════════
    story.append(h1_block("2. Embryology"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "Liver development begins at <b>3–4 weeks' gestation</b> when a hepatic foregut diverticulum "
        "buds from the ventral wall of the primitive midgut into the septum transversum. The basement "
        "membrane surrounding the liver bud is lost, and cords of bipotential <b>hepatoblasts</b> "
        "differentiate into <b>hepatocytes</b> and <b>cholangiocytes</b>. The same diverticulum gives rise "
        "to the extrahepatic bile ducts, gallbladder, and ventral pancreas.",
        body_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 3. LIGAMENTS ═══════════════════════════════════════
    story.append(h1_block("3. Ligaments and Peritoneal Reflections"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "The liver is anchored in the right upper quadrant by the hepatic veins draining into the IVC "
        "and by several ligaments formed from peritoneal reflections. All of these ligaments can be divided "
        "in a <b>bloodless plane</b> to fully mobilise the liver for surgical resection.",
        body_style))
    story.append(Spacer(1, 0.2*cm))

    lig_rows = [
        [Paragraph('<b>Ligament</b>', make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')),
         Paragraph('<b>Origin / Description</b>', make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold'))],
        ["Falciform ligament",
         "Remnant of ventral mesentery. Separates left lateral (II/III) from left medial (IV) segment along the umbilical fissure; anchors liver to anterior abdominal wall. Does NOT divide right from left lobe."],
        ["Round ligament\n(ligamentum teres)",
         "Obliterated umbilical vein. Runs from the umbilicus to the left liver hilum at the front edge of the falciform."],
        ["Ligamentum venosum\n(Arantius' ligament)",
         "Obliterated ductus venosus. Lies deep between caudate lobe and left lateral segment."],
        ["Left & right triangular\nligaments",
         "Secure both sides of the liver to the undersurface of the diaphragm."],
        ["Coronary ligaments",
         "Extend anteriorly from the triangular ligaments. The right coronary ligament also anchors the liver to the right retroperitoneum/kidney."],
        ["Hepatoduodenal ligament\n(porta hepatis)",
         "Right free edge of lesser omentum. Contains: common bile duct, hepatic artery, portal vein. Site of the Pringle manoeuvre."],
        ["Gastrohepatic ligament",
         "Lesser omentum between the stomach (lesser curve) and the liver."],
    ]
    lig_table = section_table(
        [[Paragraph(r[0] if isinstance(r[0], str) else r[0],
                    make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')),
          Paragraph(r[1] if isinstance(r[1], str) else r[1],
                    make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold'))]
         if i == 0
         else [Paragraph(r[0], make_style('TC', fontSize=9, fontName='Helvetica-Bold', textColor=DARK_RED)),
               Paragraph(r[1], make_style('TB', fontSize=9, fontName='Helvetica', textColor=DARK_GREY, leading=13))]
         for i, r in enumerate(lig_rows)],
        col_widths=[5.5*cm, 11.5*cm]
    )
    story.append(lig_table)
    story.append(Spacer(1, 0.3*cm))

    # ligaments image
    img = download_image(IMG_LIGAMENTS, 13, 9)
    if img:
        story.append(img)
        story.append(Paragraph("Fig. 1 — Anterior view of the liver showing major ligaments (Schwartz's Principles of Surgery, 11th Ed.)", caption_style))
    story.append(Spacer(1, 0.2*cm))

    story.append(Paragraph(
        "The <b>foramen of Winslow (epiploic foramen)</b> lies posterior to the porta hepatis and connects "
        "to the lesser sac. Clamping the hepatoduodenal ligament here achieves the <b>Pringle manoeuvre</b> "
        "— complete hepatic inflow occlusion.",
        note_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 4. LOBAR ANATOMY ═══════════════════════════════════
    story.append(h1_block("4. Lobar Anatomy"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "The liver is divided into <b>right and left lobes</b> by <b>Cantlie's line</b> — an imaginary plane "
        "running from the gallbladder fossa to the inferior vena cava (IVC). The <b>middle hepatic vein</b> "
        "runs within this plane.",
        body_style))

    lobar_rows = [
        ["Lobe / Structure", "Proportion of Liver Mass", "Notes"],
        ["Right lobe", "60–70%", "Lies to the right of Cantlie's line; contains segments V–VIII"],
        ["Left lobe", "~30–35%", "Contains left lateral (II/III) and left medial (IV) segments"],
        ["Caudate lobe\n(Segment I)", "~5%", "Sits anterior and left of the IVC; contains Spiegel lobe, paracaval portion, caudate process. Has DIRECT independent venous drainage into the IVC."],
    ]
    story.append(section_table(
        [[Paragraph(c, make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')) for c in lobar_rows[0]]] +
        [[Paragraph(str(c), make_style('TB', fontSize=9, fontName='Helvetica', textColor=DARK_GREY, leading=13)) for c in row]
         for row in lobar_rows[1:]],
        col_widths=[4.5*cm, 4*cm, 8.5*cm]
    ))
    story.append(Spacer(1, 0.2*cm))
    story.append(Paragraph(
        "⚠ The <b>falciform ligament is NOT the true anatomical boundary</b> between the right and left lobe. "
        "It only separates left lateral (segments II & III) from left medial (segment IV). "
        "The true boundary is Cantlie's line.",
        note_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 5. COUINAUD SEGMENTS ════════════════════════════════
    story.append(h1_block("5. Couinaud's Segmental Anatomy"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "The French anatomist <b>Couinaud</b> (early 1950s) divided the liver into <b>8 functionally "
        "independent segments</b> by studying vascular casts. Segments are numbered <b>clockwise</b> "
        "starting from the caudate lobe (I). Each segment has its own independent branch of the "
        "<b>portal vein</b>, <b>hepatic artery</b>, and <b>bile duct</b>, plus drainage via a "
        "<b>hepatic vein</b> tributary — making segment-specific (anatomical) resection possible.",
        body_style))
    story.append(Spacer(1, 0.2*cm))

    seg_rows = [
        ["Segment", "Location", "Lobe / Division"],
        ["I", "Caudate lobe — posterior, adjacent to IVC", "Caudate (unique: drains directly into IVC)"],
        ["II", "Posterior left lateral", "Left lobe — left lateral section"],
        ["III", "Anterior left lateral", "Left lobe — left lateral section"],
        ["IV (IVa / IVb)", "Left medial; IVa = cephalad, IVb = caudal", "Left lobe — left medial section"],
        ["V", "Inferior right anterior", "Right lobe — right anterior section"],
        ["VI", "Inferior right posterior", "Right lobe — right posterior section"],
        ["VII", "Superior right posterior", "Right lobe — right posterior section"],
        ["VIII", "Superior right anterior", "Right lobe — right anterior section"],
    ]
    story.append(section_table(
        [[Paragraph(c, make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')) for c in seg_rows[0]]] +
        [[Paragraph(str(c), make_style('TB', fontSize=9, fontName='Helvetica', textColor=DARK_GREY, leading=13)) for c in row]
         for row in seg_rows[1:]],
        col_widths=[2.5*cm, 8.5*cm, 6*cm]
    ))
    story.append(Spacer(1, 0.3*cm))

    img2 = download_image(IMG_COUINAUD, 13, 16)
    if img2:
        story.append(img2)
        story.append(Paragraph("Fig. 2 — Couinaud's 8 liver segments: anterior (top) and inferior (bottom) views (Schwartz's Principles of Surgery, 11th Ed.)", caption_style))

    story.append(Spacer(1, 0.2*cm))
    img3 = download_image(IMG_SEGMENTS2, 16, 9)
    if img3:
        story.append(img3)
        story.append(Paragraph("Fig. 3 — Couinaud segments with portal vein distribution, exploded view showing IVC and caudate lobe (Bailey & Love's, 28th Ed.)", caption_style))

    story.append(Spacer(1, 0.2*cm))
    story.append(Paragraph(
        "<b>Surgical note:</b> Right hepatectomy = segments V–VIII removed. "
        "Left hepatectomy = segments I–IV removed. "
        "Segment I (caudate) is surgically distinct due to its direct IVC drainage.",
        note_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 6. BLOOD SUPPLY ═════════════════════════════════════
    story.append(h1_block("6. Blood Supply"))
    story.append(Spacer(1, 0.3*cm))

    story.append(h2_style and Paragraph("<b>Dual Blood Supply</b>", h2_style))
    story.append(Paragraph(
        "The liver has a unique dual blood supply totalling ~1,500 mL/min:",
        body_style))
    supply_rows = [
        ["Vessel", "Proportion", "Source / Content"],
        ["Portal vein", "~80% of flow", "Nutrient-rich venous blood from gut, spleen, pancreas; formed by confluence of splenic + superior mesenteric veins behind neck of pancreas"],
        ["Hepatic artery", "~20% of flow", "Oxygenated blood; arises from coeliac trunk via common hepatic artery → hepatic artery proper → right + left branches"],
    ]
    story.append(section_table(
        [[Paragraph(c, make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')) for c in supply_rows[0]]] +
        [[Paragraph(str(c), make_style('TB', fontSize=9, fontName='Helvetica', textColor=DARK_GREY, leading=13)) for c in row]
         for row in supply_rows[1:]],
        col_widths=[3.5*cm, 3*cm, 10.5*cm]
    ))
    story.append(Spacer(1, 0.3*cm))

    story.append(Paragraph("<b>Hepatic Arterial Anatomy</b>", h2_style))
    story.append(Paragraph(
        "The arterial supply arises from the <b>coeliac trunk</b> → left gastric, common hepatic, "
        "splenic arteries. The common hepatic artery gives off the <b>gastroduodenal artery</b>, then "
        "continues as the <b>hepatic artery proper</b>, bifurcating into right and left hepatic arteries "
        "at the hilum. The right hepatic artery typically crosses the bile duct anteriorly or posteriorly "
        "before giving rise to the <b>cystic artery</b>.",
        body_style))
    story.append(Paragraph(
        "<b>Clinically important variants:</b><br/>"
        "&#x25BA; Replaced/accessory <b>right hepatic artery</b> arising from the SMA (runs posterior to bile duct)<br/>"
        "&#x25BA; Replaced/accessory <b>left hepatic artery</b> arising from the left gastric artery (runs in lesser omentum)",
        note_style))
    story.append(Spacer(1, 0.3*cm))

    img4 = download_image(IMG_HILUM, 15, 11)
    if img4:
        story.append(img4)
        story.append(Paragraph("Fig. 4 — Hepatic hilum anatomy showing arterial supply, portal vein, biliary tree, and coeliac trunk origin (Bailey & Love's, 28th Ed.)", caption_style))
    story.append(Spacer(1, 0.3*cm))

    story.append(Paragraph("<b>Portal Vein</b>", h2_style))
    story.append(Paragraph(
        "Formed by the confluence of the <b>splenic vein</b> and <b>superior mesenteric vein (SMV)</b> "
        "behind the neck of the pancreas. It enters the hilum and divides into right and left branches. "
        "The <b>left branch</b> has a longer (~2 cm) extrahepatic course. The portal vein often has two "
        "large right lobe branches that are outside the liver for a short length before giving a left "
        "portal vein branch running behind the left hepatic duct.",
        body_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 7. VENOUS DRAINAGE ══════════════════════════════════
    story.append(h1_block("7. Venous Drainage"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "Three major hepatic veins drain into the <b>IVC</b> just below the diaphragm:",
        body_style))
    vein_rows = [
        ["Hepatic Vein", "Segments Drained", "Notes"],
        ["Right hepatic vein", "VI, VII", "Can be exposed fully outside the liver parenchyma"],
        ["Middle hepatic vein", "IV, V, VIII", "Runs within Cantlie's line; usually joins left vein in a short common trunk"],
        ["Left hepatic vein", "II, III", "Usually forms a common trunk with middle vein before entering IVC"],
    ]
    story.append(section_table(
        [[Paragraph(c, make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')) for c in vein_rows[0]]] +
        [[Paragraph(str(c), make_style('TB', fontSize=9, fontName='Helvetica', textColor=DARK_GREY, leading=13)) for c in row]
         for row in vein_rows[1:]],
        col_widths=[4.5*cm, 4*cm, 8.5*cm]
    ))
    story.append(Spacer(1, 0.2*cm))
    story.append(Paragraph(
        "The <b>retrohepatic IVC</b> occupies a deep groove on the posterior surface of the liver. "
        "The suprahepatic IVC immediately traverses the diaphragm to enter the right atrium. "
        "A variable number of small direct hepatic veins also drain from the liver into the IVC. "
        "The right adrenal gland is adjacent to the retrohepatic IVC, draining into it via a single vein.",
        body_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 8. PORTA HEPATIS ════════════════════════════════════
    story.append(h1_block("8. The Porta Hepatis (Hilum)"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "The <b>porta hepatis</b> is a pronounced transverse fissure on the visceral surface of the liver "
        "running between the cephalad end of the fissure for the ligamentum teres and the gallbladder fossa. "
        "The neurovascular structures and lymphatics of the <b>hepatoduodenal ligament</b> enter here.",
        body_style))
    story.append(Spacer(1, 0.2*cm))
    story.append(Paragraph("<b>Classic arrangement within the hepatoduodenal ligament (anterior → posterior):</b>", body_style))
    for item in [
        "<b>Common bile duct</b> — right free edge, anterolateral",
        "<b>Hepatic artery proper</b> — medially",
        "<b>Portal vein</b> — posteriorly (largest structure)",
    ]:
        story.append(Paragraph(f"&#x25BA; {item}", bullet_style))
    story.append(Spacer(1, 0.2*cm))
    story.append(Paragraph(
        "The right and left hepatic ducts emerge from the parenchyma and unite to form the "
        "<b>common hepatic duct</b>. This is then joined by the <b>cystic duct</b> from the gallbladder "
        "to form the <b>common bile duct (CBD)</b>, which descends in the free edge of the "
        "hepatoduodenal ligament to drain into the second part of the duodenum.",
        body_style))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 9. MICROSCOPIC ANATOMY ══════════════════════════════
    story.append(h1_block("9. Microscopic Anatomy"))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph(
        "The liver contains approximately <b>100,000 hexagonal lobules</b>, each centred on a "
        "<b>central vein</b> and surrounded by six portal triads at its corners. Blood flows "
        "from the portal triads → through <b>sinusoids</b> (fenestrated capillaries) → to the "
        "central vein. Bile flows in the <b>opposite</b> direction.",
        body_style))
    story.append(Spacer(1, 0.2*cm))

    cell_rows = [
        ["Cell Type", "Location", "Key Functions"],
        ["Hepatocytes", "~80% of liver cells; in plates/cords between sinusoids",
         "Metabolism (glycolysis, gluconeogenesis), protein synthesis, bile production, detoxification (CYP450), clotting factor synthesis, vitamin storage"],
        ["Kupffer cells", "Within sinusoid lumen (attached to endothelium)",
         "Phagocytose effete RBCs and foreign antigens; part of mononuclear phagocyte system"],
        ["Sinusoidal endothelial cells", "Line the sinusoids",
         "Highly fenestrated for exchange of substrates; no basement membrane"],
        ["Hepatic stellate cells\n(Ito/perisinusoidal cells)", "Space of Disse (between hepatocytes and sinusoid)",
         "Store vitamin A (fat-soluble); activated to myofibroblasts in fibrosis → produce collagen"],
        ["Bile canaliculi", "Between adjacent hepatocytes (contralateral to sinusoid side)",
         "Drain bile in the opposite direction to blood flow toward portal tracts"],
    ]
    story.append(section_table(
        [[Paragraph(c, make_style('TH', fontSize=9, textColor=WHITE, fontName='Helvetica-Bold')) for c in cell_rows[0]]] +
        [[Paragraph(str(c), make_style('TB', fontSize=9, fontName='Helvetica', textColor=DARK_GREY, leading=13)) for c in row]
         for row in cell_rows[1:]],
        col_widths=[4*cm, 5*cm, 8*cm]
    ))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 10. FUNCTIONS ═══════════════════════════════════════
    story.append(h1_block("10. Major Functions of the Liver"))
    story.append(Spacer(1, 0.3*cm))
    func_items = [
        "Glucose metabolism: glycolysis, gluconeogenesis, glycogen storage",
        "Protein synthesis: albumin, clotting factors (I, II, V, VII, VIII, IX, X, XI), complement",
        "Bilirubin formation from haemoglobin breakdown of effete red cells",
        "Urea formation from protein catabolism (urea cycle)",
        "Drug and hormone metabolism and excretion (cytochrome P450 system)",
        "Removal of gut endotoxins and foreign antigens (Kupffer cells)",
        "Vitamin and mineral storage: A, D, E, K, and B12",
        "Bile production (~600–1000 mL/day): bile acids, phospholipids, cholesterol, bilirubin",
        "Lipid metabolism: fatty acid oxidation, ketogenesis, VLDL synthesis",
        "Immunological function as part of the mononuclear phagocyte system",
        "Temperature regulation and pH homeostasis / correction of lactic acidosis",
        "Angiotensin synthesis",
    ]
    story.append(key_point_box(func_items))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ 11. SURGICAL SUMMARY ════════════════════════════════
    story.append(h1_block("11. Key Surgical Points"))
    story.append(Spacer(1, 0.3*cm))
    surgical_items = [
        "Pringle manoeuvre: clamp hepatoduodenal ligament at foramen of Winslow to achieve complete hepatic inflow occlusion",
        "All ligaments (falciform, triangular, coronary) are divided in a bloodless plane for full liver mobilisation",
        "Right hepatectomy: removes segments V–VIII (right of Cantlie's line)",
        "Left hepatectomy: removes segments I–IV (left of Cantlie's line)",
        "Extended right hepatectomy: segments IV–VIII (trisectionectomy)",
        "Segment I (caudate) is surgically distinct — direct venous drainage to IVC, independent from the three hepatic veins",
        "The liver regenerates fully (90–100% of original volume) after resection — unique among solid organs",
        "Aberrant hepatic artery anatomy (replaced/accessory R or L hepatic artery) must be identified pre-operatively to avoid inadvertent ligation",
    ]
    story.append(key_point_box(surgical_items))
    story.append(Spacer(1, 0.4*cm))

    # ═══════════════════ SOURCES ══════════════════════════════════════════════
    story.append(HRFlowable(width="100%", thickness=0.5, color=MID_GREY))
    story.append(Spacer(1, 0.2*cm))
    story.append(Paragraph("<b>Sources</b>", make_style('SrcH', fontSize=10, fontName='Helvetica-Bold', textColor=DARK_RED)))
    for src in [
        "Schwartz's Principles of Surgery, 2-Volume Set, 11th Edition — Chapter 31: Liver",
        "Bailey and Love's Short Practice of Surgery, 28th Edition — Chapter 69",
        "Gray's Anatomy for Students — Section 4: Abdomen (Segmental Anatomy of the Liver)",
        "Sabiston Textbook of Surgery: The Biological Basis of Modern Surgical Practice — Functional Anatomy",
        "Fischer's Mastery of Surgery, 8th Edition — Chapters 173, 174",
    ]:
        story.append(Paragraph(f"&#x25CF; {src}",
            make_style('SrcL', fontSize=8.5, fontName='Helvetica', textColor=DARK_GREY, leading=13, leftIndent=10)))

    # ── build ────────────────────────────────────────────────────────────────
    doc.build(story)
    print(f"PDF saved to: {OUTPUT}")

if __name__ == "__main__":
    build()
!

Failed to create session: bad request: failed to resolve container IP after 3 attempts: no IP address found. Is the Sandbox started?

We encountered an error while processing your request. Please try again or reach out to us for help.

Try again

Running Command

mkdir -p /home/daytona/workspace/liver-anatomy && python3 -c "from reportlab.lib…

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