Hepato-Pancreatico-Biliary (HPB) Surgery ● Write a note on solid pseudopapillary neoplasms and their management (March 2026) ● Classify pancreatic tumours. Discuss the etiopathology, investigations and management of cystic tumors of pancreas (March 2026) ● Types of Biliary stricture and its management (October 2025) ● Hydatid cyst of liver (May 2025) ● Hepatocellular carcinoma (January 2025) ● Discuss the aetiopathology, clinical features, and management of "Chronic pancreatitis" (June 2023) ● Discuss the clinical features and management of Pancreatic Insulinoma (June 2023) ● Acute pancreatitis (May 2022) ● Hydatid cyst of liver (May 2022) Explain with flow charts diagrams
Definition
↓
Etiology / risk factors
↓
Pathology / pathophysiology
↓
Clinical features
↓
Investigations
↓
Classification / staging where applicable
↓
Management flowchart
↓
Complications, follow-up, prognosis
Suspected HPB disease
↓
Clinical assessment + resuscitation if unwell
↓
Baseline laboratory studies
↓
Ultrasound / contrast CT / MRI-MRCP as appropriate
↓
Tissue or cyst-fluid diagnosis only when it changes management
↓
Classify: benign vs malignant / resectable vs unresectable
↓
Multidisciplinary decision
↓
Observation | Medical/endoscopic therapy | Surgery | Oncology/palliation
Make a revision PDF covering all listed HPB topics
pancreatic cystic neoplasms AND management
hepatocellular carcinoma AND management
acute pancreatitis AND management
2025 clinical practice guideline pancreatic cystic lesions management IPMN ACG
2025 hepatocellular carcinoma clinical practice guideline management EASL
2024 acute pancreatitis clinical guideline management ACG
~/
mkdir -p "/tmp/workspace/hpb-revision-pdf/src" "/tmp/workspace/hpb-revision-pdf/output" && python -c "import reportlab; print(reportlab.Version)"
~/hpb-revision-pdf/src/create_hpb_pdf.py
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle, KeepTogether
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib.colors import HexColor
from xml.sax.saxutils import escape
OUT='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Revision_March_2026.pdf'
PAGE_W, PAGE_H=A4
navy=HexColor('#14324A'); teal=HexColor('#007C83'); blue=HexColor('#EAF4F4'); gold=HexColor('#E6A93D'); ink=HexColor('#19242B'); pale=HexColor('#F5F8FA')
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Title2', parent=styles['Title'], fontName='Helvetica-Bold', fontSize=24, leading=29, textColor=navy, alignment=TA_CENTER, spaceAfter=16))
styles.add(ParagraphStyle(name='Sub', parent=styles['Normal'], fontName='Helvetica', fontSize=11, leading=15, textColor=HexColor('#47606E'), alignment=TA_CENTER))
styles.add(ParagraphStyle(name='H1x', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=18, leading=22, textColor=navy, spaceBefore=7, spaceAfter=8))
styles.add(ParagraphStyle(name='H2x', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=12.5, leading=16, textColor=teal, spaceBefore=8, spaceAfter=4))
styles.add(ParagraphStyle(name='Bodyx', parent=styles['BodyText'], fontName='Helvetica', fontSize=8.8, leading=12.2, textColor=ink, spaceAfter=4))
styles.add(ParagraphStyle(name='Small', parent=styles['BodyText'], fontName='Helvetica', fontSize=7.6, leading=10, textColor=ink))
styles.add(ParagraphStyle(name='Flow', parent=styles['BodyText'], fontName='Helvetica-Bold', fontSize=8.4, leading=11.5, textColor=navy, alignment=TA_CENTER))
def P(s, st='Bodyx'): return Paragraph(s, styles[st])
def bullets(items): return [P('• '+x) for x in items]
def header(canvas, doc):
canvas.saveState(); canvas.setStrokeColor(teal); canvas.setLineWidth(1); canvas.line(1.5*cm, PAGE_H-1.25*cm, PAGE_W-1.5*cm, PAGE_H-1.25*cm)
canvas.setFont('Helvetica-Bold',8); canvas.setFillColor(teal); canvas.drawString(1.5*cm,PAGE_H-1.0*cm,'HPB SURGERY | RAPID REVISION')
canvas.setFont('Helvetica',8); canvas.setFillColor(HexColor('#50636F')); canvas.drawRightString(PAGE_W-1.5*cm,0.8*cm,f'Page {doc.page}')
canvas.restoreState()
def flow(steps):
cells=[]
for i,s in enumerate(steps):
cells.append(P(escape(s), 'Flow'))
if i<len(steps)-1: cells.append(P('↓','Flow'))
t=Table([cells], colWidths=[(17.0*cm)/(len(cells))]*len(cells), hAlign='CENTER')
t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),blue),('BOX',(0,0),(-1,-1),0.4,teal),('INNERGRID',(0,0),(-1,-1),0.25,HexColor('#9CCACC')),('VALIGN',(0,0),(-1,-1),'MIDDLE'),('TOPPADDING',(0,0),(-1,-1),5),('BOTTOMPADDING',(0,0),(-1,-1),5)]))
return t
def table(headers, rows, widths=None):
data=[[P('<b>'+escape(h)+'</b>','Small') for h in headers]]+[[P(escape(x),'Small') for x in r] for r in rows]
t=Table(data,colWidths=widths,repeatRows=1,hAlign='LEFT')
t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),navy),('TEXTCOLOR',(0,0),(-1,0),colors.white),('BACKGROUND',(0,1),(-1,-1),pale),('GRID',(0,0),(-1,-1),0.3,HexColor('#B7C7CE')),('VALIGN',(0,0),(-1,-1),'TOP'),('TOPPADDING',(0,0),(-1,-1),4),('BOTTOMPADDING',(0,0),(-1,-1),4)]))
return t
story=[]
story += [Spacer(1,4*cm),P('HPB Surgery', 'Title2'),P('Exam-Oriented Revision Notes', 'Title2'),P('Solid pseudopapillary neoplasm • pancreatic cystic tumours • biliary strictures • hydatid liver cyst • hepatocellular carcinoma • chronic pancreatitis • insulinoma • acute pancreatitis','Sub'),Spacer(1,1*cm),P('<b>Coverage:</b> all topics listed in the question bank. Updated for March 2026. Designed for last-minute revision, viva answers, and long-answer structure.','Sub'),Spacer(1,2*cm),P('How to write a 10-mark answer: Definition → aetiology/pathology → clinical features → investigations → classification → management flowchart → complications/prognosis.','Sub'),PageBreak()]
def section(title, definition, chunks, flowsteps=None):
story.append(P(title,'H1x')); story.append(P('<b>Definition:</b> '+definition));
for heading, content in chunks:
story.append(P(heading,'H2x'))
if isinstance(content,list): story.extend(bullets(content))
else: story.append(P(content))
if flowsteps:
story.append(P('Management flowchart','H2x')); story.append(flow(flowsteps))
story.append(Spacer(1,7))
section('1. Solid pseudopapillary neoplasm (SPN)', 'A rare, low-grade malignant epithelial pancreatic tumour, typically occurring in young women and characterised by solid and pseudopapillary areas.', [
('Key facts', ['Usually women in the 2nd-4th decades; tail/body more common than head. Large, well-encapsulated lesion with haemorrhagic-cystic degeneration.', 'Activating CTNNB1 (beta-catenin/Wnt pathway) mutation is characteristic. It is not linked to pancreatitis or usual pancreatic adenocarcinoma risk factors.', 'Symptoms: vague upper abdominal pain, early satiety or palpable mass; jaundice is unusual. Some are incidental.']),
('Investigations', ['Contrast CT or MRI: circumscribed mixed solid-cystic mass, capsule, internal haemorrhage. MRI is especially useful for blood products.', 'EUS-FNA/FNB if diagnosis is uncertain or will alter operation. Histology: pseudopapillae; immunophenotype often nuclear beta-catenin and CD10 positive.']),
('Management and prognosis', ['Resect all operable SPN in a fit patient: enucleation only for selected small lesions away from the main duct; distal pancreatectomy ± spleen preservation for body/tail; pancreaticoduodenectomy for head lesions.', 'Resectable liver/peritoneal metastases or local recurrence can also be considered for surgery. Systemic therapy has no standard established role.', 'Excellent prognosis after R0 resection, but late recurrence can occur: follow with cross-sectional imaging, commonly annually for at least 5 years.'])], ['SPN on CT/MRI','Assess resectability and duct relation','EUS tissue only if uncertain','Oncologic pancreatic resection','Long-term imaging surveillance'])
section('2. Pancreatic tumours and cystic neoplasms', 'Pancreatic tumours include exocrine, neuroendocrine, mesenchymal and secondary tumours. Pancreatic cystic lesions must first be separated from pseudocyst.', [
('Classification', []),
], None)
story.append(table(['Group','Examples'],[['Exocrine benign/premalignant','Serous cystadenoma (SCA), IPMN, mucinous cystic neoplasm (MCN)'],['Exocrine malignant','Pancreatic ductal adenocarcinoma, acinar cell carcinoma'],['Neuroendocrine','Functioning: insulinoma, gastrinoma; non-functioning pNET'],['Other solid','SPN, lymphoma, metastasis'],['Non-neoplastic cyst','Pseudocyst, congenital cyst']], [5*cm,12*cm]))
story += [P('Cystic tumour comparison','H2x'),table(['Lesion','Typical patient / imaging','Cancer risk and management'],[['SCA','Older woman; central scar, microcystic, no duct communication','Near-benign. Observe if asymptomatic and certain diagnosis; operate for symptoms/diagnostic doubt.'],['MCN','Women; body/tail; macrocystic, ovarian-type stroma; no duct communication','Premalignant. Resection in fit patients, especially ≥4 cm, nodule, symptoms or concerning features.'],['IPMN','Main duct, branch duct or mixed; communicates with duct; mucin','Main duct/mixed: resect if fit. Branch duct: risk stratify and surveil or resect.'],['SPN','Young woman; solid-cystic encapsulated','Resect.']], [3*cm,6.3*cm,7.7*cm]),P('Work-up','H2x')] + bullets(['History of pancreatitis/trauma and alcohol use suggests pseudocyst. Obtain CA 19-9 selectively, liver tests and glycaemic status.', 'Pancreas-protocol CT or MRI/MRCP: MRI/MRCP best for duct communication and surveillance. EUS ± FNA when diagnosis is unclear or worrisome features are present and result changes management.', 'Cyst fluid: CEA supports mucinous nature; amylase suggests duct communication/pseudocyst; cytology has low sensitivity but high-grade atypia is important.']) + [P('IPMN risk features','H2x'),table(['High-risk stigmata','Worrisome features'],[['Obstructive jaundice with head cyst; enhancing mural nodule/solid component; main pancreatic duct ≥10 mm; positive high-grade dysplasia cytology','Cyst ≥3 cm; mural nodule; thick/enhancing wall; main duct 5-9 mm; abrupt duct calibre change/distal atrophy; pancreatitis; raised CA 19-9; growth']], [8.5*cm,8.5*cm]),P('Cyst management flowchart','H2x'),flow(['Cyst found','CT or MRI/MRCP: define type + duct communication','High-risk stigmata?','Yes: MDT and resection if fit','No: EUS if worrisome/uncertain','Low-risk: MRI-based surveillance'])) ,PageBreak()]
section('3. Biliary strictures', 'A focal or diffuse narrowing of the bile duct causing impaired bile drainage. Treat every indeterminate stricture as malignant until adequately evaluated.', [
('Classification', ['<b>By cause:</b> benign (postoperative injury, chronic pancreatitis, PSC, IgG4-related disease, stones, ischaemia/radiation) versus malignant (cholangiocarcinoma, pancreatic/ampullary cancer, gallbladder cancer, nodal metastasis).', '<b>By level:</b> intrahepatic, hilar/perihilar, distal extrahepatic. Hilar strictures are commonly described by Bismuth-Corlette: I below confluence; II at confluence; IIIa right extension; IIIb left extension; IV bilateral extension.', '<b>Post-cholecystectomy injury:</b> use Strasberg system. Minor leak/injury may be A-D; complete/major duct injuries are E1-E5, broadly corresponding to level of hilar involvement.']),
('Clinical features and tests', ['Cholestatic jaundice, pruritus, pale stools/dark urine, recurrent cholangitis. Weight loss, painless progressive jaundice and mass suggest malignancy.', 'LFTs, bilirubin, coagulation profile, CA 19-9 interpreted cautiously in cholestasis. Ultrasound first; contrast CT/MRI-MRCP for level, mass, vessels and resectability.', 'ERCP provides brushings/biopsy and drainage of distal accessible strictures. EUS assesses distal lesions/nodes. PTC is useful when hilar obstruction cannot be drained endoscopically. Negative brush cytology does not exclude cancer.']),
('Management', ['Resuscitate cholangitis: antibiotics plus urgent biliary decompression. Benign dominant strictures often need serial balloon dilation and temporary multiple plastic stents; treat cause.', 'Postoperative major stricture: control sepsis, drain biloma, define anatomy and refer early to HPB unit. Definitive repair is tension-free Roux-en-Y hepaticojejunostomy after inflammation settles, unless selected early expert repair.', 'Malignant: MDT staging. Resect when appropriate. Palliate unresectable obstruction with endoscopic metal stent (distal) or selective endoscopic/percutaneous drainage (hilar), plus systemic oncologic care.'])], ['Jaundice/cholangitis','LFT + US','CT/MRCP ± EUS','ERCP/PTC for sampling and drainage','Benign: dilate/stent or HJ','Malignant: stage → resect or palliate'])
section('4. Hydatid cyst of liver', 'Cystic echinococcosis of the liver caused principally by larval Echinococcus granulosus.', [
('Aetiopathology', ['Dog/canid is definitive host; sheep commonly intermediate host. Humans ingest eggs and become accidental intermediate hosts. Oncospheres reach liver via portal blood.', 'Cyst consists of pericyst (host fibrous tissue), ectocyst (laminated membrane) and endocyst/germinal layer producing daughter cysts and hydatid sand. Liver is involved in roughly 50-75% of cases.']),
('Presentation and diagnosis', ['Often asymptomatic. Right upper quadrant discomfort, mass, nausea; complicated cyst may cause fever, cholangitis, jaundice, rupture/anaphylaxis, bronchobiliary fistula or secondary infection.', 'Ultrasound is the primary classifier. CT maps size, calcification, daughter cysts, biliary communication and operative planning. Serology supports diagnosis but does not exclude it if negative.', '<b>WHO ultrasound stages:</b> CE1 active unilocular simple cyst; CE2 active multivesicular daughter cysts; CE3a detached membrane; CE3b daughter cysts in solid matrix; CE4 inactive heterogeneous; CE5 inactive calcified.']),
('Treatment principles', ['Avoid unprotected spillage: anaphylaxis and peritoneal seeding are risks. Albendazole is used peri-procedurally and for selected uncomplicated or disseminated disease.', 'Observe inactive uncomplicated CE4/CE5 lesions with imaging. PAIR (puncture-aspiration-injection-reaspiration) is suitable for selected uncomplicated CE1/CE3a lesions where expertise exists.', 'Surgery for large superficial cysts, multiple daughter cysts, biliary communication, infection, rupture, compression or unsuitable PAIR. Options: partial pericystectomy/deroofing with management of residual cavity; formal resection rarely. Look actively for and close cystobiliary communication.'])], ['US/CT + serology','WHO stage + assess biliary communication','Inactive CE4/5: observe','Selected CE1/3a: albendazole ± PAIR','Complicated/large CE2/3b: surgery + albendazole'])
section('5. Hepatocellular carcinoma (HCC)', 'Primary malignant tumour of hepatocytes, usually arising in cirrhosis or chronic liver disease.', [
('Risk factors and surveillance', ['Cirrhosis from HBV, HCV, alcohol-associated liver disease, metabolic dysfunction-associated steatotic liver disease, haemochromatosis and other chronic liver diseases. HBV can cause HCC without cirrhosis.', 'Surveillance in at-risk populations: ultrasound with or without AFP every 6 months, according to local guideline/pathway.']),
('Diagnosis and staging', ['Multiphasic CT or MRI: arterial phase hyperenhancement with portal/delayed washout and capsule is diagnostic in an at-risk liver. Biopsy if imaging is indeterminate or diagnosis alters care.', 'Assess tumour burden, macrovascular invasion/extrahepatic spread, performance status and liver reserve: Child-Pugh, MELD, portal hypertension, future liver remnant. BCLC is a practical treatment-linked staging framework.']),
('Management', ['Very early/early disease: resection for preserved liver function without significant portal hypertension; ablation for small tumours, especially when surgery unsuitable; transplantation for selected patients within accepted criteria (classically Milan: single ≤5 cm or ≤3 lesions each ≤3 cm, no macrovascular invasion/metastasis).', 'Intermediate disease: transarterial therapy such as TACE for selected liver-limited disease; radioembolisation (Y-90) or other locoregional approaches in appropriate cases.', 'Advanced disease: systemic therapy, often immune-checkpoint inhibitor based combinations in eligible patients; select according to liver function, bleeding/variceal risk, autoimmune contraindications and local protocol. Best supportive care for terminal disease.'])], ['At-risk patient','US ± AFP every 6 months','Suspicious lesion → multiphasic CT/MRI','Stage: liver reserve + tumour + PS','Curative: resection / ablation / transplant','Locoregional or systemic therapy'])
section('6. Chronic pancreatitis', 'A progressive fibro-inflammatory pancreatic disease causing irreversible structural damage, pain, and loss of exocrine and endocrine function.', [
('Aetiology and pathogenesis', ['Use TIGAR-O: Toxic-metabolic (alcohol, smoking, hypercalcaemia, hypertriglyceridaemia), Idiopathic, Genetic (PRSS1, SPINK1, CFTR), Autoimmune, Recurrent/severe acute pancreatitis, Obstructive (stricture, tumour, divisum).', 'Repeated injury activates pancreatic stellate cells → collagen deposition → fibrosis, duct distortion/strictures/stones → pain, exocrine insufficiency and diabetes. Smoking accelerates progression.']),
('Clinical features and investigations', ['Recurrent or persistent epigastric pain radiating to back, weight loss, steatorrhoea, malnutrition and diabetes. Complications: pseudocyst, biliary/duodenal obstruction, splenic vein thrombosis, pseudoaneurysm, pancreatic cancer.', 'CT detects calcification, duct dilation and complications. MRI/MRCP ± secretin shows duct anatomy. EUS detects early changes and excludes cancer. Faecal elastase supports exocrine pancreatic insufficiency.']),
('Management', ['Stop alcohol and smoking; analgesia using a stepwise multidisciplinary plan; nutritional review, small frequent meals, pancreatic enzyme replacement with meals and acid suppression when required; fat-soluble vitamins, calcium/vitamin D and diabetes management.', 'Endoscopic therapy for obstructing duct stone/stricture: ERCP stone extraction/stenting, often ESWL for large radiopaque duct stones. Drain symptomatic pseudocyst endoscopically where suitable.', 'Surgery gives durable decompression/resection in selected refractory painful obstructive disease: lateral pancreaticojejunostomy (Puestow) for dilated duct; Frey/Beger for inflammatory head mass; pancreaticoduodenectomy when head disease or cancer suspicion.'])], ['Confirm CP + exclude cancer','Lifestyle + nutrition + enzymes + analgesia','Obstruction? CT/MRCP/EUS','Endoscopic duct clearance/stent ± ESWL','Persistent pain or head mass → surgical drainage/resection'])
section('7. Pancreatic insulinoma', 'Usually solitary, benign pancreatic neuroendocrine tumour that secretes insulin autonomously, producing fasting hypoglycaemia.', [
('Clinical features', ['Whipple triad: symptoms of hypoglycaemia, low plasma glucose at symptom time, and relief after glucose. Neuroglycopenic symptoms include confusion, behaviour change, seizure or coma; adrenergic features include sweating, tremor and palpitations.', 'Most are small and intrapancreatic. Consider MEN1 when multifocal, young age or family history.']),
('Diagnosis', ['Supervised 72-hour fast: document low plasma glucose with inappropriately raised insulin, C-peptide and proinsulin; negative sulfonylurea screen distinguishes exogenous secretagogue use. Insulin antibodies if factitious insulin is possible.', 'Localise only after biochemical confirmation: pancreas-protocol CT/MRI, EUS; specialised functional imaging or selective arterial calcium stimulation with hepatic venous sampling when occult.']),
('Management', ['Treat hypoglycaemia immediately with oral/IV glucose. Frequent carbohydrate intake; diazoxide ± somatostatin analogue can bridge to operation or control unresectable disease.', 'Curative surgery: enucleation for small superficial lesion away from main duct; distal pancreatectomy for body/tail or deep lesion; pancreaticoduodenectomy rarely for head lesion. Intraoperative ultrasound improves localisation.', 'Malignant/metastatic pNET: debulk/resect where feasible; somatostatin analogue, targeted agents, peptide receptor radionuclide therapy or chemotherapy in specialist care.'])], ['Whipple triad','72-hour fast: insulin/C-peptide/proinsulin high','CT/MRI + EUS localisation','Resect: enucleate or pancreatectomy','Monitor glucose and recurrence'])
section('8. Acute pancreatitis', 'Acute inflammatory pancreatic injury. Diagnosis requires any 2 of: typical pain, lipase/amylase >3× upper limit of normal, or characteristic imaging.', [
('Causes and severity', ['Gallstones and alcohol are common. Also hypertriglyceridaemia, hypercalcaemia, drugs, post-ERCP, trauma, tumour/obstruction, autoimmune and genetic causes.', 'Revised Atlanta: mild = no organ failure/complications; moderately severe = transient organ failure (<48 h) and/or local/systemic complication; severe = persistent organ failure >48 h.']),
('Assessment', ['Early severity/risk assessment: SIRS, organ function, haematocrit/BUN trend, oxygenation and comorbidity. Ultrasound in all to seek gallstones. CT is not required routinely at presentation; obtain contrast CT after about 48-72 h if diagnosis uncertain, severe course or complications suspected.', 'MRCP/EUS for suspected choledocholithiasis without cholangitis. ERCP is urgent for acute biliary pancreatitis with cholangitis, and indicated for persistent biliary obstruction.']),
('Management', ['ABC, oxygen if required, opioid analgesia, antiemetics and goal-directed IV crystalloid resuscitation, commonly lactated Ringer solution. Avoid fluid overload; frequent reassessment of urine output, BUN/haematocrit, lungs and haemodynamics.', 'Early oral feeding with low-fat solid diet once tolerated; enteral tube feeding for severe disease if oral intake fails. Do not use prophylactic antibiotics in sterile necrosis.', 'Mild gallstone pancreatitis: same-admission laparoscopic cholecystectomy. Infected necrosis: antibiotics that penetrate necrosis and delayed step-up drainage/debridement where possible, ideally after walling-off (often ~4 weeks).'])], ['Diagnose: 2 of 3 criteria','Assess severity + US for gallstones','LR resuscitation + analgesia + early enteral feeding','Cholangitis/persistent obstruction → ERCP','Necrosis: sterile no antibiotics; infected → delayed step-up','Index-admission cholecystectomy if mild biliary AP'])
story += [PageBreak(),P('Rapid diagrams and exam recall','H1x'),P('Pancreatic cyst decision map','H2x'),P('<b>Pseudocyst?</b> Prior pancreatitis + high cyst fluid amylase → treat only if symptomatic/complicated. <b>Mucinous?</b> MCN/IPMN → malignancy-risk assessment. <b>Duct communication?</b> IPMN. <b>Central scar/microcysts?</b> SCA. <b>Young woman, solid-cystic?</b> SPN.','Bodyx'),P('Pancreatic surgery map','H2x'),table(['Lesion position','Common operation'],[['Head/uncinate','Pancreaticoduodenectomy (Whipple)'],['Neck/body/tail','Distal pancreatectomy ± splenic preservation'],['Small superficial benign/low-grade lesion away from duct','Enucleation']], [7*cm,10*cm]),P('Important red flags','H2x')] + bullets(['Biliary stricture with cholangitis: urgent drainage, not repeated diagnostic delay.', 'Hydatid cyst: never aspirate casually. Plan only in a protected expert protocol.', 'HCC: assess liver reserve and portal hypertension before resection.', 'Chronic pancreatitis: new jaundice, weight loss or changing pain warrants exclusion of pancreatic cancer.', 'Acute pancreatitis: organ failure and infected necrosis drive mortality; do not give routine prophylactic antibiotics.']) + [P('Selected sources and update note','H2x'),P('Core surgical concepts were cross-checked against <i>Schwartz’s Principles of Surgery, 11th ed.</i>, <i>Current Surgical Therapy, 14th ed.</i>, <i>Maingot’s Abdominal Operations</i>, and <i>Bailey & Love’s Short Practice of Surgery, 28th ed.</i> via the medical textbook library. Current management framing incorporates the 2024 ACG acute pancreatitis guideline (PMID 38857482) and the 2025 EASL HCC guideline (PMID 39690085). Local multidisciplinary protocols take precedence for individual care. This is a study aid, not patient-specific clinical advice.','Small')]
doc=SimpleDocTemplate(OUT,pagesize=A4,rightMargin=1.5*cm,leftMargin=1.5*cm,topMargin=1.65*cm,bottomMargin=1.3*cm,title='HPB Surgery Revision March 2026',author='Orris')
doc.build(story,onFirstPage=header,onLaterPages=header)
print(OUT)
python "/tmp/workspace/hpb-revision-pdf/src/create_hpb_pdf.py" && python -c "from pypdf import PdfReader; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Revision_March_2026.pdf'; r=PdfReader(p); print('pages',len(r.pages)); print('first', r.pages[0].extract_text()[:200]); print('last',r.pages[-1].extract_text()[:300])"
python -c "p='/tmp/workspace/hpb-revision-pdf/src/create_hpb_pdf.py'; s=open(p).read(); s=s.replace(\"flow(['Cyst found','CT or MRI/MRCP: define type + duct communication','High-risk stigmata?','Yes: MDT and resection if fit','No: EUS if worrisome/uncertain','Low-risk: MRI-based surveillance'])) ,PageBreak()]\", \"flow(['Cyst found','CT or MRI/MRCP: define type + duct communication','High-risk stigmata?','Yes: MDT and resection if fit','No: EUS if worrisome/uncertain','Low-risk: MRI-based surveillance']), PageBreak()]\"); open(p,'w').write(s)" && python "/tmp/workspace/hpb-revision-pdf/src/create_hpb_pdf.py" && python -c "from pypdf import PdfReader; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Revision_March_2026.pdf'; r=PdfReader(p); print('pages',len(r.pages)); print('first',r.pages[0].extract_text()[:100]); print('last',r.pages[-1].extract_text()[-300:])"
python -c "import fitz; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Revision_March_2026.pdf'; d=fitz.open(p); [d[i].get_pixmap(matrix=fitz.Matrix(1.2,1.2),alpha=False).save(f'/tmp/workspace/hpb-revision-pdf/output/preview_{i+1}.png') for i in (0,1,3,7)]; print('rendered',len(d),'pages')"
python -c "import pdfplumber; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Revision_March_2026.pdf'; pdf=pdfplumber.open(p); print('pages',len(pdf.pages)); [print(i+1, len(page.extract_text() or ''), round(page.height), round(page.width)) for i,page in enumerate(pdf.pages)]"
HPB Surgery Revision March 2026
PDF Document · PDF
Create a longer detailed version with labelled diagrams
labelled diagram pancreas anatomy head body tail pancreatic duct bile duct
labelled liver segments biliary anatomy diagram hepatic duct
2025 pancreatic cystic lesions consensus guideline IPMN management high risk stigmata
2024 ACG acute pancreatitis guideline management ERCP fluid resuscitation early feeding
2025 EASL hepatocellular carcinoma guideline treatment surveillance resection transplantation
~/hpb-revision-pdf
~/hpb-revision-pdf/src
~/hpb-revision-pdf/src/create_hpb_detailed.py
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.colors import HexColor
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle, KeepTogether, Flowable
from reportlab.graphics.shapes import Drawing, Rect, Circle, Line, String, Polygon
from xml.sax.saxutils import escape
OUT='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Detailed_Revision_with_Labelled_Diagrams_August_2026.pdf'
W,H=A4
navy=HexColor('#12344D'); teal=HexColor('#007C83'); pale=HexColor('#EAF5F4'); gold=HexColor('#E6A83B'); red=HexColor('#A63D40'); ink=HexColor('#1C2930'); gray=HexColor('#526570')
S=getSampleStyleSheet()
S.add(ParagraphStyle(name='TitleX',parent=S['Title'],fontName='Helvetica-Bold',fontSize=26,leading=31,textColor=navy,alignment=TA_CENTER,spaceAfter=13))
S.add(ParagraphStyle(name='SubX',parent=S['Normal'],fontSize=11,leading=15,textColor=gray,alignment=TA_CENTER))
S.add(ParagraphStyle(name='H1X',parent=S['Heading1'],fontName='Helvetica-Bold',fontSize=18,leading=22,textColor=navy,spaceBefore=8,spaceAfter=8))
S.add(ParagraphStyle(name='H2X',parent=S['Heading2'],fontName='Helvetica-Bold',fontSize=12.4,leading=15,textColor=teal,spaceBefore=8,spaceAfter=4))
S.add(ParagraphStyle(name='B',parent=S['BodyText'],fontSize=9,leading=12.4,textColor=ink,spaceAfter=4))
S.add(ParagraphStyle(name='SM',parent=S['BodyText'],fontSize=7.7,leading=9.7,textColor=ink))
S.add(ParagraphStyle(name='Box',parent=S['BodyText'],fontName='Helvetica-Bold',fontSize=8.2,leading=10.5,textColor=navy,alignment=TA_CENTER))
def P(x,sty='B'): return Paragraph(x,S[sty])
def bullets(xs): return [P('• '+x) for x in xs]
def tbl(head,rows,widths):
data=[[P(escape(x),'SM') for x in head]]+[[P(escape(str(x)),'SM') for x in r] for r in rows]
t=Table(data,colWidths=widths,repeatRows=1,hAlign='LEFT')
t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),navy),('TEXTCOLOR',(0,0),(-1,0),colors.white),('FONTNAME',(0,0),(-1,0),'Helvetica-Bold'),('BACKGROUND',(0,1),(-1,-1),HexColor('#F6F9FA')),('GRID',(0,0),(-1,-1),.3,HexColor('#A5C8CA')),('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),5),('RIGHTPADDING',(0,0),(-1,-1),5),('TOPPADDING',(0,0),(-1,-1),4),('BOTTOMPADDING',(0,0),(-1,-1),4)]))
return t
def flow(steps):
cells=[]
for i,x in enumerate(steps):
cells.append(P(escape(x),'Box'))
if i<len(steps)-1: cells.append(P('→','Box'))
widths=[]
for i in range(len(cells)): widths.append(.55*cm if i%2 else (17.0-(len(steps)-1)*.55)/len(steps)*cm)
t=Table([cells],colWidths=widths,hAlign='LEFT')
t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),pale),('BOX',(0,0),(-1,-1),.5,teal),('INNERGRID',(0,0),(-1,-1),.3,HexColor('#9AC8C8')),('VALIGN',(0,0),(-1,-1),'MIDDLE'),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7)]))
return t
def note(title,text):
t=Table([[P('<b>'+escape(title)+'</b><br/>'+escape(text),'SM')]],colWidths=[17*cm])
t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),HexColor('#FFF8E7')),('BOX',(0,0),(-1,-1),.5,gold),('LEFTPADDING',(0,0),(-1,-1),7),('RIGHTPADDING',(0,0),(-1,-1),7),('TOPPADDING',(0,0),(-1,-1),6),('BOTTOMPADDING',(0,0),(-1,-1),6)])); return t
def labelled(kind):
d=Drawing(460,170)
def label(x,y,s): d.add(String(x,y,s,fontName='Helvetica',fontSize=8,fillColor=navy))
if kind=='pancreas':
d.add(Polygon([70,80,120,112,220,110,300,95,365,72,300,48,190,43,115,53],fillColor=HexColor('#F7CFAE'),strokeColor=navy,strokeWidth=1.4))
d.add(Circle(338,72,11,fillColor=HexColor('#F4B183'),strokeColor=red)); d.add(Line(90,77,350,72,strokeColor=teal,strokeWidth=2)); d.add(Line(285,72,315,125,strokeColor=teal,strokeWidth=2)); d.add(Line(315,125,390,125,strokeColor=teal,strokeWidth=2))
for x,y,tx,ty,s in [(86,125,35,145,'Tail'),(190,126,170,150,'Body'),(300,118,285,150,'Head'),(338,55,350,28,'Uncinate'),(195,65,150,25,'Main pancreatic duct'),(387,130,358,148,'Common bile duct')]: d.add(Line(x,y,tx,ty,strokeColor=gray)); label(tx,ty,s)
label(18,10,'Figure: pancreatic anatomy and ducts (schematic)')
elif kind=='liver':
d.add(Polygon([65,75,120,130,265,145,400,110,425,65,350,35,170,28,90,45],fillColor=HexColor('#D98F70'),strokeColor=navy,strokeWidth=1.2))
d.add(Line(250,35,250,140,strokeColor=HexColor('#7E4837'),strokeWidth=2)); d.add(Line(250,105,175,70,strokeColor=HexColor('#7E4837'),strokeWidth=1.5)); d.add(Line(250,105,340,70,strokeColor=HexColor('#7E4837'),strokeWidth=1.5))
for x,y,s in [(125,102,'Left lobe'),(318,105,'Right lobe'),(230,148,'Middle hepatic vein'),(75,18,'Caudate'),(345,18,'Portal triad')]: label(x,y,s)
d.add(Line(300,75,360,22,strokeColor=gray)); label(360,18,'Right hepatic duct'); d.add(Line(175,70,90,15,strokeColor=gray)); label(20,10,'Left hepatic duct')
label(145,2,'Figure: liver and hilar anatomy (schematic)')
elif kind=='hydatid':
d.add(Circle(150,82,61,fillColor=HexColor('#F2D48D'),strokeColor=navy,strokeWidth=1.2)); d.add(Circle(150,82,49,fillColor=HexColor('#F9EDC9'),strokeColor=gold)); d.add(Circle(150,82,31,fillColor=HexColor('#EEF6E5'),strokeColor=teal));
for x,y in [(137,93),(160,95),(147,66),(169,76)]: d.add(Circle(x,y,5,fillColor=HexColor('#B3D18D'),strokeColor=teal))
for x1,y1,x2,y2,s in [(90,116,24,140,'Pericyst'),(102,82,20,82,'Ectocyst'),(130,53,48,28,'Endocyst / germinal layer'),(161,95,265,115,'Daughter cysts'),(165,74,272,47,'Hydatid sand')]: d.add(Line(x1,y1,x2,y2,strokeColor=gray)); label(x2,y2,s)
label(55,4,'Figure: hydatid cyst layers (schematic)')
elif kind=='biliary':
d.add(Line(230,145,230,110,strokeColor=teal,strokeWidth=5)); d.add(Line(160,155,230,110,strokeColor=teal,strokeWidth=5)); d.add(Line(300,155,230,110,strokeColor=teal,strokeWidth=5)); d.add(Line(230,110,230,25,strokeColor=teal,strokeWidth=6)); d.add(Circle(268,105,20,fillColor=HexColor('#B7D77D'),strokeColor=navy)); d.add(Line(270,125,230,110,strokeColor=teal,strokeWidth=4)); d.add(Rect(220,60,20,13,fillColor=red,strokeColor=red));
for x,y,s in [(120,158,'Left hepatic duct'),(294,158,'Right hepatic duct'),(276,104,'Gallbladder'),(245,60,'Stricture'),(244,20,'Common bile duct')]: label(x,y,s)
label(95,2,'Figure: extrahepatic biliary tree and a distal stricture')
return d
def header(canv,doc):
canv.saveState(); canv.setStrokeColor(teal); canv.line(1.5*cm,H-1.25*cm,W-1.5*cm,H-1.25*cm); canv.setFillColor(teal); canv.setFont('Helvetica-Bold',8); canv.drawString(1.5*cm,H-1.02*cm,'HPB SURGERY | DETAILED REVISION'); canv.setFillColor(gray); canv.setFont('Helvetica',8); canv.drawRightString(W-1.5*cm,.75*cm,'Page %d'%doc.page); canv.restoreState()
story=[]
story += [Spacer(1,1.6*cm),P('HPB Surgery','TitleX'),P('Detailed Exam Revision Notes','TitleX'),P('Solid pseudopapillary neoplasm • pancreatic tumours and cysts • biliary strictures • hydatid liver cyst • hepatocellular carcinoma • chronic pancreatitis • insulinoma • acute pancreatitis','SubX'),Spacer(1,.8*cm),note('How to use this book','Each topic follows an examination-ready pattern: definition, aetiopathology, clinical features, investigations, management, complications and a labelled schematic. Management statements are for revision and require local multidisciplinary adaptation.'),Spacer(1,.7*cm),P('Contents','H2X'),tbl(['Section','Focus'],[['1','Solid pseudopapillary neoplasm'],['2','Classification and cystic tumours of pancreas'],['3','Biliary strictures'],['4','Hydatid cyst of liver'],['5','Hepatocellular carcinoma'],['6','Chronic pancreatitis'],['7','Pancreatic insulinoma'],['8','Acute pancreatitis']], [2*cm,15*cm]),PageBreak()]
# SPN
story += [P('1. Solid Pseudopapillary Neoplasm (SPN)','H1X'),P('A rare low-grade malignant epithelial pancreatic tumour, also called solid pseudopapillary tumour or Frantz tumour. It classically affects young women and has an excellent prognosis after complete resection.'),labelled('pancreas'),P('Aetiopathology and pathology','H2X'),bullets(['Usually occurs in females in the second to fourth decades. Most are sporadic; CTNNB1 mutation with aberrant β-catenin/Wnt signalling is characteristic.','Typically a large, well circumscribed, encapsulated solid-cystic lesion. Haemorrhagic degeneration creates mixed solid and cystic areas. Histology shows delicate pseudopapillae with myxoid stroma.','It has malignant potential: invasion, recurrence or metastasis are uncommon but possible, especially with vascular/perineural invasion or incomplete excision.']),P('Clinical features and diagnosis','H2X'),tbl(['Domain','Key points'],[['Presentation','Often incidental; vague epigastric pain, early satiety or palpable mass. Jaundice and acute pancreatitis are unusual.'],['Tests','Routine biochemistry is often normal. Tumour markers have no diagnostic role.'],['Imaging','Pancreas-protocol CT or MRI: encapsulated heterogeneous lesion with solid enhancing portions, haemorrhage and cystic degeneration. MRI is sensitive to blood products.'],['Tissue','EUS-guided biopsy only when imaging is equivocal or diagnosis changes the plan. Avoid unnecessary biopsy if a clearly resectable lesion is proceeding to surgery.']], [3.1*cm,13.9*cm]),P('Management flowchart','H2X'),flow(['Suspected SPN on CT/MRI','Assess resectability and fitness','MDT review','Complete surgical excision','Pathology and surveillance']),P('Operation','H2X'),bullets(['Head: pancreaticoduodenectomy or selected parenchyma-sparing resection. Body/tail: distal pancreatectomy, preferably spleen-preserving when oncologically appropriate. Small superficial lesions away from the main duct may be enucleated.','Aim for negative margins. Routine major lymphadenectomy is generally not required because nodal metastases are rare. Resect isolated recurrence/metastases when feasible.','Follow-up imaging is reasonable because delayed recurrence can occur.'] ),note('Exam pearl','A young woman with a large encapsulated mixed solid-cystic pancreatic mass is SPN until proven otherwise. The answer is resection, not prolonged cyst surveillance.'),PageBreak()]
# cysts
story += [P('2. Pancreatic Tumours and Cystic Neoplasms','H1X'),P('Classification of pancreatic tumours','H2X'),tbl(['Group','Examples'],[['Exocrine solid','Ductal adenocarcinoma, acinar cell carcinoma, pancreatoblastoma, solid pseudopapillary neoplasm'],['Neuroendocrine','Functioning: insulinoma, gastrinoma, glucagonoma, VIPoma, somatostatinoma. Non-functioning pancreatic neuroendocrine tumour.'],['Cystic neoplasms','Intraductal papillary mucinous neoplasm (IPMN), mucinous cystic neoplasm (MCN), serous cystadenoma (SCA), SPN, cystic neuroendocrine tumour.'],['Non-neoplastic cystic lesions','Pseudocyst, walled-off necrosis, retention cyst, congenital cyst.']], [4*cm,13*cm]),labelled('pancreas'),P('Cystic tumour comparison','H2X'),tbl(['Lesion','Signature features','Management'],[['SCA','Older patient, microcystic honeycomb, central scar; no duct communication.','Almost always benign. Observe if asymptomatic and diagnosis is secure; operate for symptoms, growth or doubt.'],['MCN','Women; body/tail; macrocystic, ovarian-type stroma; no duct communication.','Premalignant. Resect in fit patients, particularly ≥4 cm, symptomatic, mural nodule or other concerning features.'],['IPMN','Mucin-producing; main duct, branch duct or mixed; communicates with main duct.','Main duct/mixed usually resect if fit. Branch duct requires risk stratification.'],['SPN','Young women; encapsulated mixed solid-cystic lesion.','Resection.'],['Pseudocyst','History of pancreatitis; high cyst-fluid amylase; no epithelial lining.','Treat only if symptomatic, infected, enlarging or causing obstruction.']], [2.7*cm,7.1*cm,7.2*cm]),P('Investigations','H2X'),bullets(['History: pancreatitis, trauma, alcohol, familial pancreatic cancer syndrome, symptoms of obstruction or endocrine activity. Baseline LFT, glucose and selectively CA 19-9.','MRI/MRCP is preferred for duct communication and surveillance. Pancreas-protocol CT evaluates solid components, calcification and surgical anatomy.','EUS ± FNA is appropriate when diagnosis is uncertain or a result will change treatment. Cyst-fluid CEA supports mucinous cyst, amylase indicates duct communication, and cytology may show high-grade atypia but has limited sensitivity.']),P('IPMN risk pathway','H2X'),tbl(['High-risk stigmata','Worrisome features'],[['Obstructive jaundice from a head cyst; enhancing mural nodule or solid component; main duct ≥10 mm; cytology with high-grade dysplasia/cancer.','Cyst ≥3 cm; growth; pancreatitis attributable to cyst; raised CA 19-9; main duct 5-9 mm; small mural nodule; thick/enhancing wall; abrupt duct calibre change with distal atrophy or nodes.']], [8.5*cm,8.5*cm]),flow(['Pancreatic cyst','CT or MRI/MRCP','High-risk stigmata?','Yes: MDT and resect if fit','No: EUS for worrisome or uncertain lesion','Low-risk: MRI surveillance']),note('Revision warning','Surveillance intervals differ among Kyoto, ACG, European and other guidance. In exams, state that MRI/EUS surveillance is individualized by cyst size, phenotype, age, surgical fitness and interval change.'),PageBreak()]
# biliary
story += [P('3. Biliary Strictures','H1X'),P('A biliary stricture is a fixed narrowing of the bile duct causing impaired bile drainage. The immediate clinical question is whether it is benign or malignant; untreated obstruction can lead to cholangitis and secondary biliary cirrhosis.'),labelled('biliary'),P('Classification','H2X'),tbl(['Class','Causes'],[['Benign','Post-cholecystectomy bile-duct injury; anastomotic stricture after transplant/biliary surgery; chronic pancreatitis; primary sclerosing cholangitis; IgG4-related disease; stone-related inflammation; radiation.'],['Malignant','Cholangiocarcinoma: intrahepatic, perihilar (Klatskin), distal; pancreatic head cancer; ampullary cancer; gallbladder cancer; nodal compression/metastasis.'],['By level','Intrahepatic, perihilar, extrahepatic/distal. Bismuth-Corlette classifies perihilar strictures by extension into right/left ducts.']], [3.4*cm,13.6*cm]),P('Clinical features and work-up','H2X'),bullets(['Painless progressive jaundice, pruritus, dark urine, pale stool and weight loss suggest malignancy. Fever, pain and jaundice indicate acute cholangitis and require urgent source control.','LFT: cholestatic pattern. Ultrasound establishes duct dilatation and gallbladder status. Contrast CT or MRI/MRCP maps level, length, vascular involvement and metastatic disease.','ERCP permits brushings/biopsy and therapy of distal obstruction; EUS helps sample a distal mass or nodes. Percutaneous transhepatic cholangiography is useful for hilar obstruction or failed ERCP. Negative cytology does not exclude cancer.']),P('Management algorithm','H2X'),flow(['Jaundice / cholangitis','Resuscitate, antibiotics if infected','US + CT/MRCP','Define benign vs malignant; obtain tissue when needed','Drain if septic or clinically necessary','Definitive endoscopic, surgical or oncologic treatment']),P('Benign strictures','H2X'),bullets(['Endoscopic balloon dilatation plus sequential plastic stents, or fully covered removable metal stent in selected distal strictures. Repeated sessions may be required.','A high biliary injury or failed endotherapy is treated by Roux-en-Y hepaticojejunostomy in an experienced HPB unit. Control sepsis and drain collections first; delayed reconstruction is often safer once inflammation settles.','PSC strictures: exclude cholangiocarcinoma; treat dominant symptomatic strictures with carefully selected short balloon dilation.']),P('Malignant strictures','H2X'),bullets(['Resectable distal cholangiocarcinoma or pancreatic head cancer: pancreaticoduodenectomy. Perihilar cholangiocarcinoma: tailored hepatectomy with bile-duct resection and caudate resection where appropriate.','Unresectable obstruction: endoscopic metal stent for distal disease; percutaneous or combined drainage for complex hilar obstruction. Refer for systemic therapy and symptom-directed palliation.']),note('Exam pearl','Do not confuse diagnostic ERCP with MRCP. MRCP maps non-invasively; ERCP is mainly therapeutic or for tissue sampling.'),PageBreak()]
# hydatid
story += [P('4. Hydatid Cyst of Liver','H1X'),P('Cystic echinococcosis is zoonotic infection by the larval stage of Echinococcus granulosus. Humans are accidental intermediate hosts. The liver is involved most frequently, followed by lung.'),labelled('hydatid'),P('Life cycle and pathology','H2X'),flow(['Dog/carnivore: definitive host','Eggs in faeces','Human or sheep ingests eggs','Oncospheres enter portal circulation','Liver hydatid cyst forms']),bullets(['The cyst has an outer host-derived pericyst, laminated ectocyst and inner germinal endocyst. Daughter cysts and hydatid sand contain viable protoscolices.','Cysts enlarge slowly. Complications result from rupture, secondary infection, pressure effects, or communication with bile ducts.']),P('Clinical features and complications','H2X'),tbl(['Feature','Details'],[['Clinical','Often asymptomatic. Dull right upper-quadrant pain, hepatomegaly or mass; fever if infected.'],['Biliary rupture','Jaundice, biliary colic, cholangitis; hydatid membranes may appear in bile.'],['Intraperitoneal rupture','Anaphylaxis and secondary peritoneal seeding.'],['Other','Secondary infection/abscess, portal hypertension, thoracic extension.']], [4*cm,13*cm]),P('Diagnosis','H2X'),bullets(['Ultrasound is first-line and identifies daughter cysts, detached membranes and calcification. CT defines site, size, complications and extrahepatic extension; MRI/MRCP assesses biliary communication.','Serology supports diagnosis but sensitivity varies by cyst site and stage. Avoid unplanned needle aspiration because of spillage/anaphylaxis risk.']),P('WHO-style stage-based management','H2X'),tbl(['Cyst pattern','Usual strategy'],[['Inactive CE4/CE5, uncomplicated','Observe with serial imaging if inactive.'],['Small active CE1 or CE3a (<5 cm)','Albendazole may be suitable.'],['Uncomplicated CE1 / CE3a suitable for puncture','PAIR: puncture-aspiration-instillation-reaspiration plus albendazole, only in an expert setting.'],['Daughter-cyst rich CE2 / CE3b, large superficial, infected, ruptured or biliary communication','Surgery, often pericystectomy or controlled deroofing with management of bile leak; albendazole adjunct.']], [5.7*cm,11.3*cm]),P('Operative principles','H2X'),bullets(['Prevent spillage: isolate field with scolicidal-soaked packs per local protocol, aspirate carefully, remove daughter cysts and membranes, identify/close cysto-biliary communications, deal with residual cavity.','Radical pericystectomy or hepatic resection is selected for peripheral, complex or recurrent disease. Less radical procedures may be appropriate for deep lesions.','Albendazole is used pre- and post-procedure under liver-function and blood-count monitoring.'],),note('Danger','PAIR is not appropriate when there is biliary communication, major rupture risk, or a complex lesion not amenable to safe percutaneous management.'),PageBreak()]
# HCC
story += [P('5. Hepatocellular Carcinoma (HCC)','H1X'),P('HCC is the principal primary malignant tumour of the liver. It generally arises in cirrhosis but can occur without cirrhosis, particularly in chronic hepatitis B or fibrolamellar HCC.'),labelled('liver'),P('Aetiology and surveillance','H2X'),tbl(['Risk factors','Surveillance'],[['Cirrhosis of any cause; chronic HBV or HCV; alcohol-associated liver disease; metabolic dysfunction-associated steatotic liver disease; aflatoxin exposure; haemochromatosis and other metabolic liver disease.','At-risk patients usually undergo ultrasound-based surveillance at approximately 6-month intervals, with or without AFP according to local guideline and risk group.']], [8.5*cm,8.5*cm]),P('Diagnosis and staging','H2X'),bullets(['Triphasic CT or dynamic MRI: arterial phase hyperenhancement with portal/delayed washout and capsule appearance supports diagnosis in an at-risk liver. LI-RADS standardizes imaging reporting.','Assess liver reserve: Child-Pugh, MELD, portal hypertension, bilirubin, performance status and future liver remnant. Stage tumour burden with cross-sectional imaging and multidisciplinary review.','Biopsy is used when imaging is indeterminate, liver is non-cirrhotic, or tissue is required for another diagnosis/clinical trial.']),P('Treatment framework','H2X'),flow(['HCC confirmed or highly probable','Assess tumour burden + liver function + performance status','Curative options if feasible','Liver-directed therapy if intermediate','Systemic therapy if advanced','Best supportive / palliative care throughout']),tbl(['Clinical situation','Treatment options'],[['Solitary lesion, preserved liver function','Resection if adequate future liver remnant and no significant portal hypertension.'],['Within transplant criteria with decompensated cirrhosis','Liver transplantation. Milan criteria: single ≤5 cm or up to 3 lesions each ≤3 cm, no macrovascular invasion/extrahepatic spread.'],['Small unresectable lesion','Thermal ablation, commonly microwave or radiofrequency.'],['Liver-confined multifocal disease','TACE, radioembolization (Y-90), selected external-beam radiation; consider downstaging/bridging to transplant.'],['Vascular invasion / metastases / progression','Systemic treatment, often an immune-checkpoint based combination when eligible; select according to liver function, bleeding risk and contraindications.']], [5.3*cm,11.7*cm]),P('High-yield complications and follow-up','H2X'),bullets(['Treat underlying liver disease, portal-hypertension complications and nutritional decline in parallel.','After resection or ablation, recurrence surveillance with cross-sectional imaging and AFP where informative is essential.','All decisions should be made in an HPB-liver tumour board.']),note('Current framing','The 2025 EASL HCC guideline emphasizes risk-stratified surveillance, standardized imaging, multidisciplinary sequencing of resection, transplantation, locoregional therapy, radiation and systemic therapy.'),PageBreak()]
# chronic pancreatitis
story += [P('6. Chronic Pancreatitis','H1X'),P('Chronic pancreatitis is a progressive fibro-inflammatory pancreatic disease leading to irreversible structural damage, chronic pain, exocrine insufficiency and diabetes.'),labelled('pancreas'),P('Aetiology: TIGAR-O','H2X'),tbl(['Mnemonic','Examples'],[['Toxic-metabolic','Alcohol, smoking, hypercalcaemia, hypertriglyceridaemia, renal failure, drugs.'],['Idiopathic','Early-onset or late-onset idiopathic disease.'],['Genetic','PRSS1, SPINK1, CFTR, CTRC and syndromic disease.'],['Autoimmune','IgG4-related type 1; type 2 autoimmune pancreatitis.'],['Recurrent/severe acute pancreatitis','Repeated injury promotes fibrosis.'],['Obstructive','Duct stone/stricture, pancreas divisum, tumour, ampullary obstruction.']], [3.6*cm,13.4*cm]),P('Pathogenesis and presentation','H2X'),flow(['Repeated pancreatic injury','Stellate-cell activation','Collagen deposition and fibrosis','Duct distortion / stones','Pain + exocrine and endocrine failure']),bullets(['Pain: recurrent or continuous epigastric pain radiating to back, often postprandial. Weight loss and opioid dependence may develop.','Exocrine failure: steatorrhoea, malnutrition and fat-soluble vitamin deficiency. Endocrine failure causes pancreatogenic (type 3c) diabetes.','Complications: pseudocyst, biliary/duodenal obstruction, splenic vein thrombosis, pseudoaneurysm, ascites/fistula and pancreatic cancer.']),P('Investigations','H2X'),bullets(['CT identifies calcification, duct dilatation, stones, atrophy and complications. MRI/MRCP ± secretin assesses duct anatomy. EUS detects early parenchymal/ductal change and excludes malignancy.','Faecal elastase helps assess exocrine insufficiency. Check nutrition, glucose/HbA1c, calcium, triglycerides, IgG4 where indicated and genetic causes in selected patients.']),P('Stepwise management','H2X'),flow(['Stop alcohol and smoking','Nutrition + pancreatic enzymes','Analgesia and treat diabetes','Endoscopic duct therapy if obstruction','Surgery for persistent pain / structural disease']),P('Treatment detail','H2X'),tbl(['Domain','Approach'],[['Lifestyle/nutrition','Alcohol abstinence and smoking cessation; small frequent meals; dietitian review; replace fat-soluble vitamins and micronutrients.'],['Exocrine insufficiency','Pancreatic enzyme replacement with meals and snacks; add acid suppression if response inadequate.'],['Pain','Paracetamol/NSAID where safe, neuropathic agents in selected cases; avoid long-term opioid escalation when possible.'],['Endotherapy','ERCP with stone extraction/lithotripsy, stricture dilatation and temporary stenting for dominant obstructed duct. Drain symptomatic pseudocysts.'],['Surgery','Dilated duct: longitudinal pancreaticojejunostomy (Puestow/Partington-Rochelle). Head-dominant disease: Frey, Beger or pancreaticoduodenectomy depending morphology. Distal disease: distal pancreatectomy.']], [3.5*cm,13.5*cm]),note('Exam pearl','Surgery is not a last resort in a patient with obstructed duct and disabling pain. Early referral is appropriate when endoscopic drainage fails or repeated procedures are needed.'),PageBreak()]
# insulinoma
story += [P('7. Pancreatic Insulinoma','H1X'),P('Insulinoma is the commonest functioning pancreatic neuroendocrine tumour. Most are benign, solitary and small. They cause hyperinsulinaemic hypoglycaemia.'),labelled('pancreas'),P('Clinical diagnosis','H2X'),tbl(['Whipple triad','Meaning'],[['1. Symptoms compatible with hypoglycaemia','Sweating, tremor, palpitations, confusion, behavioural change, seizure or coma.'],['2. Low plasma glucose at time of symptoms','Document venous glucose.'],['3. Relief after glucose','Symptoms resolve with carbohydrate administration.']], [5.2*cm,11.8*cm]),P('Biochemical confirmation','H2X'),bullets(['During spontaneous hypoglycaemia or supervised fast: low glucose with inappropriately detectable/elevated insulin, C-peptide and proinsulin; suppressed beta-hydroxybutyrate.','Screen for sulfonylurea/meglitinide exposure. Exogenous insulin causes high insulin with suppressed C-peptide.','A supervised 72-hour fast is the reference test when spontaneous sampling is unavailable. Consider MEN1, especially in young patients or multifocal disease.']),P('Localisation','H2X'),flow(['Biochemical endogenous hyperinsulinism','Pancreas-protocol CT or MRI','EUS if occult / for surgical planning','Selective arterial calcium stimulation with hepatic venous sampling if still occult','Intraoperative ultrasound and palpation']),P('Management','H2X'),bullets(['Treat hypoglycaemia immediately with oral carbohydrate if conscious, otherwise IV dextrose or glucagon. Frequent carbohydrate intake is a bridge to definitive therapy.','Diazoxide suppresses insulin release and is used when surgery is delayed, contraindicated or disease is metastatic. Somatostatin analogues benefit selected tumours.','Curative treatment is surgery. Enucleate a small superficial lesion safely separated from the main duct. Perform distal pancreatectomy for body/tail lesions close to duct or larger tumours; pancreaticoduodenectomy is occasionally required for deep head lesions.','For malignant/unresectable disease, manage in neuroendocrine MDT: cytoreduction where feasible, liver-directed therapy, somatostatin analogues and systemic targeted/radioligand options as appropriate.']),P('Key operative safety point','H2X'),note('Duct distance matters','Do not enucleate a lesion abutting the main pancreatic duct. Intraoperative ultrasound defines lesion number, vascular relation and duct proximity, reducing fistula risk.'),PageBreak()]
# AP
story += [P('8. Acute Pancreatitis','H1X'),P('Acute pancreatitis is acute inflammation of the pancreas. Diagnosis requires any 2 of 3: characteristic pain, serum lipase or amylase ≥3 times upper limit of normal, or characteristic imaging.'),labelled('pancreas'),P('Aetiology','H2X'),tbl(['Common','Other causes'],[['Gallstones; alcohol; hypertriglyceridaemia; post-ERCP.','Drugs, hypercalcaemia, trauma, infection, autoimmune pancreatitis, genetic predisposition, pancreas divisum, tumour/ampullary obstruction, ischaemia and idiopathic disease.']], [8.5*cm,8.5*cm]),P('Severity: revised Atlanta','H2X'),tbl(['Category','Definition'],[['Mild','No organ failure and no local/systemic complication.'],['Moderately severe','Transient organ failure (<48 h) and/or local or systemic complication.'],['Severe','Persistent organ failure >48 h, single or multiple organ systems.']], [4*cm,13*cm]),P('Early management','H2X'),flow(['Confirm diagnosis and assess severity','Lactated Ringer fluid, analgesia, antiemetics','Check aetiology: US, LFT, triglyceride, calcium','Early oral/enteral feeding as tolerated','Escalate to HDU/ICU if organ failure']),bullets(['Fluid: use goal-directed, moderately aggressive resuscitation with repeated assessment of haemodynamics, urine output, haematocrit, urea/creatinine and signs of overload. Lactated Ringer solution is commonly preferred.','Analgesia: multimodal analgesia including opioids when required. Give oxygen/organ support as indicated. Do not use prophylactic antibiotics for sterile necrosis.','Nutrition: begin oral low-fat solid diet in mild disease as symptoms permit. In severe disease, enteral nasogastric or nasojejunal feeding is preferred over parenteral nutrition.']),P('Investigations and imaging','H2X'),bullets(['Ultrasound for biliary cause in all patients. CT is not routinely required on day 1 if diagnosis is certain. Contrast CT after about 48-72 hours is useful if diagnosis is unclear, patient fails to improve, or severe disease/complication is suspected.','MRCP/EUS can detect choledocholithiasis or structural causes when ultrasound is non-diagnostic. ERCP is therapeutic, not routine diagnostic imaging.']),P('Biliary pancreatitis and ERCP','H2X'),tbl(['Situation','Action'],[['Acute cholangitis or persistent biliary obstruction','Urgent ERCP for duct clearance/drainage.'],['Mild gallstone pancreatitis without cholangitis','Early same-admission laparoscopic cholecystectomy once clinically improving.'],['No clear duct obstruction','MRCP/EUS rather than diagnostic ERCP.']], [6.5*cm,10.5*cm]),P('Local complications and step-up approach','H2X'),flow(['Acute necrotic collection / walled-off necrosis','Observe if sterile and improving','Suspect infection: clinical deterioration or gas in collection','Antibiotics penetrating necrosis + delay intervention if possible','Step-up drainage then endoscopic/minimally invasive necrosectomy']),bullets(['Collections: acute peripancreatic fluid collection, pseudocyst, acute necrotic collection and walled-off necrosis are defined by content and timing.','Infected necrosis warrants antibiotics and source control. Where possible, delay invasive intervention until walled-off, often around 4 weeks, unless deterioration mandates earlier treatment.','A step-up strategy begins with percutaneous or endoscopic drainage, followed by minimally invasive necrosectomy only if necessary.']),note('Current update','The 2024 ACG guideline and contemporary reviews support early feeding, avoidance of prophylactic antibiotics and avoidance of overly aggressive fluid loading. Use ERCP selectively for cholangitis or obstruction.'),PageBreak()]
# final consolidated
story += [P('Final 1-Minute Examination Checklist','H1X'),tbl(['Topic','Must-write points'],[['SPN','Young female; encapsulated mixed solid-cystic mass; β-catenin pathway; complete resection.'],['Pancreatic cyst','Differentiate IPMN, MCN, SCA and pseudocyst; MRI/MRCP, EUS selectively; high-risk IPMN features drive resection.'],['Biliary stricture','Benign vs malignant; CT/MRCP mapping; ERCP/PTC drainage and tissue; hepaticojejunostomy for complex benign injury.'],['Hydatid','Dog-sheep cycle; daughter cysts; stage-based albendazole, PAIR or surgery; beware biliary communication and anaphylaxis.'],['HCC','Cirrhosis/HBV risk; dynamic CT/MRI; resection, transplant, ablation, TACE/Y-90, systemic therapy by stage/liver reserve.'],['Chronic pancreatitis','TIGAR-O; pain, calcification, exocrine failure; enzymes, endotherapy and morphology-directed surgery.'],['Insulinoma','Whipple triad; supervised fast; localise then enucleate/resect.'],['Acute pancreatitis','2 of 3 diagnostic criteria; LR/analgesia/early feeding; no prophylactic antibiotics; ERCP for cholangitis/obstruction; step-up for infected necrosis.']], [4.2*cm,12.8*cm]),P('Sources and currency','H2X'),P('Prepared as an exam revision resource from surgical and medical textbook-library material consulted in this conversation, supplemented by current guideline framing. Recent reference points include ACG Clinical Guideline: Management of Acute Pancreatitis (2024, PMID 38857482), EASL Clinical Practice Guidelines on HCC (2025, PMID 39690085), and contemporary pancreatic cyst consensus literature. This educational document is not a substitute for local protocols or patient-specific specialist care.'),Spacer(1,.5*cm),note('How to score well','Start with a definition and classification, then use an algorithm. State the reason for each test and give the management decision points, not merely a list of procedures.')]
doc=SimpleDocTemplate(OUT,pagesize=A4,rightMargin=1.5*cm,leftMargin=1.5*cm,topMargin=1.7*cm,bottomMargin=1.4*cm,title='HPB Surgery Detailed Revision')
doc.build(story,onFirstPage=header,onLaterPages=header)
print(OUT)
python "/tmp/workspace/hpb-revision-pdf/src/create_hpb_detailed.py" && python -c "from pypdf import PdfReader; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Detailed_Revision_with_Labelled_Diagrams_August_2026.pdf'; r=PdfReader(p); print('pages',len(r.pages)); print([len(x.extract_text() or '') for x in r.pages])"
~/hpb-revision-pdf/src/create_hpb_detailed.py
Successfully replaced 1 instance(s) of the string in '/tmp/workspace/hpb-revision-pdf/src/create_hpb_detailed.py'
python "/tmp/workspace/hpb-revision-pdf/src/create_hpb_detailed.py" && python -c "from pypdf import PdfReader; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Detailed_Revision_with_Labelled_Diagrams_August_2026.pdf'; r=PdfReader(p); print('pages',len(r.pages)); print('chars', [len(x.extract_text() or '') for x in r.pages]); print('first',r.pages[0].extract_text()[:150]); print('last',r.pages[-1].extract_text()[-250:])"
python -c "import pdfplumber; p='/tmp/workspace/hpb-revision-pdf/output/HPB_Surgery_Detailed_Revision_with_Labelled_Diagrams_August_2026.pdf'; pdf=pdfplumber.open(p); [print('\\n---PAGE',i+1,'---\\n',(pg.extract_text() or '')[:900]) for i,pg in enumerate(pdf.pages)]"