I want a long essay on UGI scopy. From Anatony to steps of ugi scopy and results and various Diagnosis. Make me a word document on whole thing

Reading File
Reading File
Finding Sources
Finding Sources
Searching the Web

upper GI endoscopy procedure anatomy steps findings diagnosis comprehensive

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

mkdir -p /tmp/workspace/ugi-scopy && ls /tmp/workspace/

Writing File

~/ugi-scopy/create_ugiscopy_doc.py

from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

doc = Document()

# ---- Page margins ----
section = doc.sections[0]
section.left_margin = Inches(1.2)
section.right_margin = Inches(1.2)
section.top_margin = Inches(1.0)
section.bottom_margin = Inches(1.0)

# ---- Default Normal style ----
normal_style = doc.styles['Normal']
normal_style.font.name = 'Calibri'
normal_style.font.size = Pt(11)

# ---- Heading 1 style ----
h1 = doc.styles['Heading 1']
h1.font.name = 'Calibri'
h1.font.size = Pt(16)
h1.font.bold = True
h1.font.color.rgb = RGBColor(0x1F, 0x49, 0x7D)

# ---- Heading 2 style ----
h2 = doc.styles['Heading 2']
h2.font.name = 'Calibri'
h2.font.size = Pt(13)
h2.font.bold = True
h2.font.color.rgb = RGBColor(0x2E, 0x74, 0xB5)

# ---- Heading 3 style ----
h3 = doc.styles['Heading 3']
h3.font.name = 'Calibri'
h3.font.size = Pt(11)
h3.font.bold = True
h3.font.color.rgb = RGBColor(0x1F, 0x49, 0x7D)

def add_heading(doc, text, level):
    p = doc.add_heading(text, level=level)
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    return p

def add_para(doc, text, bold=False, italic=False, size=11):
    p = doc.add_paragraph()
    run = p.add_run(text)
    run.bold = bold
    run.italic = italic
    run.font.size = Pt(size)
    p.paragraph_format.space_after = Pt(6)
    return p

def add_bullet(doc, text):
    p = doc.add_paragraph(text, style='List Bullet')
    p.paragraph_format.space_after = Pt(3)
    return p

def add_sub_bullet(doc, text):
    p = doc.add_paragraph(text, style='List Bullet 2')
    p.paragraph_format.space_after = Pt(2)
    return p

# ============================================================
# TITLE PAGE
# ============================================================
title_para = doc.add_paragraph()
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = title_para.add_run('Upper Gastrointestinal Endoscopy (UGI Scopy)')
run.bold = True
run.font.size = Pt(24)
run.font.color.rgb = RGBColor(0x1F, 0x49, 0x7D)

sub_para = doc.add_paragraph()
sub_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run2 = sub_para.add_run('A Comprehensive Clinical Reference')
run2.italic = True
run2.font.size = Pt(14)
run2.font.color.rgb = RGBColor(0x2E, 0x74, 0xB5)

doc.add_paragraph()
date_para = doc.add_paragraph()
date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run3 = date_para.add_run('Anatomy | Procedure | Findings | Diagnoses | Therapeutic Interventions')
run3.font.size = Pt(12)
run3.italic = True

doc.add_paragraph()
doc.add_paragraph()

# ============================================================
# SECTION 1: INTRODUCTION
# ============================================================
add_heading(doc, '1. Introduction', 1)
add_para(doc, '''Upper gastrointestinal (UGI) endoscopy, formally termed esophagogastroduodenoscopy (EGD) or oesophagogastroduodenoscopy (OGD), is the most commonly performed endoscopic procedure in clinical gastroenterology. It provides direct, real-time visual examination of the mucosa of the esophagus, stomach, and first and second portions of the duodenum using a thin, flexible, fiberoptic or video endoscope introduced through the mouth.

The procedure has evolved from rudimentary rigid instruments in the 19th century to the sophisticated video-endoscope systems used today. The first endoscopic device was introduced in 1806 by Philip Bozzini, who developed a "Lichtleiter" (light conductor) for examination of canals and cavities of the human body. A rigid endoscope was first used in a human in 1853. The pivotal milestone came in the mid-20th century when Rudolf Schindler - widely regarded as the father of modern endoscopy - pioneered gastroscopy using a semirigid gastroscope. The invention of flexible fiberoptic technology by Basil Hirschowitz in the 1950s revolutionized endoscopy. Video endoscopy, introduced in the mid-1980s, further transformed the field by using a charge-coupled device (CCD) at the tip of the endoscope to generate high-resolution electronic images displayed on a video monitor.

Today, upper GI endoscopy is recognized as the gold standard for diagnosing and treating disorders of the upper gastrointestinal tract - surpassing barium contrast radiography in sensitivity, specificity, and therapeutic capability.''')

# ============================================================
# SECTION 2: ANATOMY OF THE UPPER GASTROINTESTINAL TRACT
# ============================================================
add_heading(doc, '2. Anatomy of the Upper Gastrointestinal Tract', 1)

add_para(doc, '''A thorough understanding of the anatomy of the upper GI tract is fundamental to performing a safe and complete endoscopy. The upper GI tract comprises three main segments: the esophagus, the stomach, and the duodenum. Each has distinct anatomical landmarks visible during endoscopy.''')

add_heading(doc, '2.1 The Esophagus', 2)
add_para(doc, '''The esophagus is a muscular tube approximately 25 cm in length in adults. It begins at the upper esophageal sphincter (UES), also known as the cricopharyngeal muscle, which lies at the level of the C5-C6 vertebrae. The esophagus passes through the posterior mediastinum and traverses the diaphragm at the esophageal hiatus (T10 level) before terminating at the lower esophageal sphincter (LES) and the gastroesophageal (GE) junction.

Layers of the esophageal wall (from inside out):
- Mucosa: non-keratinized stratified squamous epithelium (pale pink in appearance)
- Submucosa: loose connective tissue with mucous glands
- Muscularis propria: inner circular and outer longitudinal muscle layers (upper third is striated; lower two-thirds are smooth muscle)
- Adventitia: the esophagus lacks a serous coat

Endoscopic landmarks in the esophagus:
- Upper esophageal sphincter (UES): the first point of entry; marked by the cricopharyngeal bar
- Mid-esophagus: smooth, straight, peristaltic tube with pale pink squamous mucosa
- Esophagogastric (EG) junction / Z-line: an irregular serrated demarcation where the pale pink squamous epithelium of the esophagus transitions to the orange-red columnar mucosa of the stomach. Palisading vessels mark the end of the distal esophagus. The Z-line is typically located 38-40 cm from the incisors.
- Lower esophageal sphincter (LES): the functional transition zone; normally closed at rest and located at the level of the diaphragmatic hiatus.''')

add_heading(doc, '2.2 The Stomach', 2)
add_para(doc, '''The stomach is a dilatable muscular reservoir that lies in the left upper quadrant of the abdomen. It is divided into several anatomical regions:

- Cardia: the region immediately below the GE junction; surrounds the cardiac orifice
- Fundus: the dome-shaped superior part that lies above and to the left of the cardiac orifice; often contains a gas bubble on imaging
- Body (Corpus): the main tubular portion; characterized by prominent rugal folds along the greater curvature
- Antrum: the distal portion, which is smooth and funnel-shaped; rugal folds disappear as the antrum is entered
- Pyloric canal and pylorus: the narrow muscular channel connecting the stomach to the duodenum; normally round and observed opening and closing rhythmically during endoscopy
- Incisura angularis: a smooth curved notch on the lesser curvature dividing the body from the antrum; visible at the 12 o'clock position during endoscopy

Curvatures:
- Lesser curvature: the shorter medial border
- Greater curvature: the longer lateral border bearing prominent mucosal rugae

Layers of the stomach (from inside out):
- Mucosa: lined by simple columnar epithelium with gastric pits and glands
- Submucosa
- Muscularis externa: three layers (oblique, circular, longitudinal)
- Serosa (visceral peritoneum)

Endoscopic orientation in the stomach:
When the scope is correctly positioned in the gastric body, the posterior wall is at the 3 o'clock position, the lesser curvature at 12 o'clock, the anterior wall at 9 o'clock, and the greater curvature at 6 o'clock.''')

add_heading(doc, '2.3 The Duodenum', 2)
add_para(doc, '''The duodenum is the first and shortest portion of the small intestine, measuring approximately 25-30 cm in length. It forms a C-shaped loop around the head of the pancreas and is divided into four parts:

- First part (D1) / Duodenal bulb (cap): the most proximal segment; smooth-walled without folds; a frequent site of inflammation and ulceration
- Second part (D2) / Descending duodenum: contains plicae circulares (Kerckring folds); the major papilla (Ampulla of Vater) opens on its medial wall, typically visualized at the 9 o'clock position; bile and pancreatic secretions enter here
- Third part (D3) / Horizontal duodenum: crosses the midline
- Fourth part (D4): ascends to the duodenojejunal flexure (Ligament of Treitz)

A standard 120 cm endoscope typically allows visualization up to D2. Visualization beyond the Ligament of Treitz requires a longer enteroscope.

Endoscopic landmarks:
- Duodenal bulb: smooth mucosa without folds; immediately post-pyloric
- Ampulla of Vater: visible in D2 at the 9 o'clock position on the medial wall as a small papillary elevation with a central orifice (a side-viewing scope is required for detailed assessment)
- Plicae circulares (valves of Kerckring): prominent circular folds visible in D2 and beyond''')

# ============================================================
# SECTION 3: THE ENDOSCOPE - EQUIPMENT
# ============================================================
add_heading(doc, '3. The Endoscope: Equipment and Components', 1)

add_para(doc, '''Modern upper GI endoscopes are flexible video instruments with the following key components:''')

add_bullet(doc, 'Insertion tube: a flexible tube approximately 1000-1100 mm in working length and 8-13 mm in diameter')
add_bullet(doc, 'Distal tip: contains the CCD imaging chip, light source fibers, air/water nozzle, and working channel opening')
add_bullet(doc, 'Bending section: the distal 3-10 cm of the insertion tube capable of four-directional angulation (up/down and left/right)')
add_bullet(doc, 'Working (biopsy) channel: 2.0 to 3.7 mm diameter channel for passing instruments (forceps, snares, needles, balloons, stents)')
add_bullet(doc, 'Air/water/suction channels: for insufflation, lens washing, and suction')
add_bullet(doc, 'Control head (handle): held in the left hand; contains up-down deflection knob (controlled by left thumb), the smaller left-right deflection knob, and the air/water/suction valves (operated by left index and middle fingers). The right hand controls the shaft for advancing, withdrawing, and rotating')
add_bullet(doc, 'Video processor and monitor: the CCD generates high-definition color images displayed in real time')
add_bullet(doc, 'Light source: xenon or LED cold light source transmitted via fiber bundles')

add_para(doc, '\nSpecialized endoscopes include:')
add_bullet(doc, 'Side-viewing duodenoscope: required for ERCP and ampullary visualization')
add_bullet(doc, 'Enteroscope: longer scope (200+ cm) for visualization beyond the ligament of Treitz')
add_bullet(doc, 'Transnasal endoscope (TNE): small-caliber scope (5-6 mm) passed transnasally; used for unsedated endoscopy')
add_bullet(doc, 'Therapeutic (wide-channel) endoscope: larger working channel (3.7 mm) for interventions')
add_bullet(doc, 'Chromoendoscope / NBI endoscope: with narrow band imaging (NBI) or chromoendoscopy capability for mucosal characterization')

# ============================================================
# SECTION 4: INDICATIONS AND CONTRAINDICATIONS
# ============================================================
add_heading(doc, '4. Indications and Contraindications', 1)

add_heading(doc, '4.1 Indications', 2)
add_para(doc, 'Upper GI endoscopy is indicated across a wide spectrum of diagnostic and therapeutic scenarios:')

add_para(doc, 'Diagnostic indications:', bold=True)
add_bullet(doc, 'Persistent abdominal pain despite appropriate empirical therapy')
add_bullet(doc, 'Abdominal pain with alarm features: weight loss, anemia, hematemesis, dysphagia, or age >45 years')
add_bullet(doc, 'Gastrointestinal bleeding: acute hematemesis, melena, or chronic blood loss / iron deficiency anemia')
add_bullet(doc, 'Dysphagia (difficulty swallowing) or odynophagia (painful swallowing)')
add_bullet(doc, 'Persistent or recurrent gastroesophageal reflux (GERD) not responding to medical therapy')
add_bullet(doc, 'Persistent nausea and/or vomiting of unknown etiology')
add_bullet(doc, 'Cancer screening: Barrett esophagus surveillance, genetic syndromes, history of gastric polyps or cancer')
add_bullet(doc, 'Assessment of abnormalities identified on imaging: ulcers, mass lesions, stenosis, fistulas')
add_bullet(doc, 'Suspected Helicobacter pylori infection (for biopsy and urease testing)')
add_bullet(doc, 'Evaluation of portal hypertension and esophageal varices')
add_bullet(doc, 'Celiac disease: duodenal biopsy for villous atrophy assessment')
add_bullet(doc, 'Foreign body ingestion')
add_bullet(doc, 'Unexplained weight loss or anorexia in older patients')

add_para(doc, '\nTherapeutic indications:', bold=True)
add_bullet(doc, 'Treatment of upper GI hemorrhage (injection, thermal coagulation, clipping, banding)')
add_bullet(doc, 'Dilation of esophageal, anastomotic, or pyloric strictures')
add_bullet(doc, 'Variceal banding or sclerotherapy')
add_bullet(doc, 'Polypectomy and endoscopic mucosal resection (EMR)')
add_bullet(doc, 'Endoscopic submucosal dissection (ESD) for early cancers')
add_bullet(doc, 'Stent placement for malignant or benign strictures')
add_bullet(doc, 'Percutaneous endoscopic gastrostomy (PEG) placement')
add_bullet(doc, 'Radiofrequency ablation (RFA) of Barrett esophagus')
add_bullet(doc, 'Foreign body removal')
add_bullet(doc, 'Endoscopic ultrasound (EUS)-guided interventions')

add_heading(doc, '4.2 Contraindications', 2)
add_para(doc, 'Absolute contraindications:', bold=True)
add_bullet(doc, 'Known or suspected perforation of the gastrointestinal tract')
add_bullet(doc, 'Fulminant epiglottitis or severe oropharyngeal obstruction')
add_bullet(doc, 'Patient refusal after informed consent')

add_para(doc, '\nRelative contraindications:', bold=True)
add_bullet(doc, 'Severe coagulopathy (especially if biopsy or therapeutic intervention planned)')
add_bullet(doc, 'Hemodynamic instability / uncontrolled shock')
add_bullet(doc, 'Recent myocardial infarction or pulmonary embolism')
add_bullet(doc, 'Uncooperative patient (may require general anesthesia)')
add_bullet(doc, 'Large Zenker diverticulum (risk of perforation on scope insertion)')
add_bullet(doc, 'Severe cardiac or pulmonary compromise')
add_bullet(doc, 'Pregnancy (first trimester; proceed only if urgently indicated)')

# ============================================================
# SECTION 5: PRE-PROCEDURE PREPARATION
# ============================================================
add_heading(doc, '5. Pre-Procedure Preparation', 1)

add_heading(doc, '5.1 Patient Preparation', 2)
add_para(doc, '''Proper patient preparation is essential for a safe, successful, and complete examination. Key elements include:

Fasting:
- No solids for at least 6-8 hours prior to the procedure
- No liquids for at least 4 hours prior
- A clear liquid diet for 24-48 hours may be required in patients with suspected gastric outlet obstruction or severe gastroparesis
- In patients with upper GI bleeding, intravenous erythromycin administered prior to endoscopy acts as a prokinetic and significantly improves endoscopic visualization by accelerating gastric emptying

Medication review:
- Anticoagulants and antiplatelet agents: must be reviewed against current BSG/ESGE guidelines for risk stratification (see ESGE 2021 guidelines). For elective procedures with low bleeding risk, aspirin may be continued; P2Y12 inhibitors and oral anticoagulants typically require cessation according to a standardized protocol
- NSAIDs and iron supplements should be noted as they affect mucosal appearance

Informed consent:
- Patient must be counseled on the indications, procedure steps, sedation options, risks (bleeding, perforation, aspiration, adverse reactions to sedation), and alternatives
- Written consent should be obtained

Laboratory and imaging testing:
- Healthy patients: routine pre-procedural testing is not recommended by ASGE guidelines
- Selective testing is required for: women of childbearing age (pregnancy test), patients with active bleeding (coagulation studies, hemoglobin/hematocrit, blood type and screen), patients with endocrine/renal/hepatic dysfunction, and those with new cardiac or pulmonary symptoms (chest X-ray)''')

add_heading(doc, '5.2 Sedation', 2)
add_para(doc, '''Sedation enhances patient comfort and cooperation. Options include:

Conscious (Moderate) Sedation:
- Most commonly used in routine UGI endoscopy
- Intravenous midazolam (2.5-5 mg) as an anxiolytic/amnestic, often combined with an opioid (fentanyl 25-100 mcg) for analgesia
- Patient remains responsive to verbal stimuli

Deep Sedation / Monitored Anesthesia Care (MAC):
- Propofol administered by an anesthesiologist or trained nurse anesthetist
- Used for prolonged, complex, or therapeutic procedures
- Provides deeper sedation with faster recovery

Topical pharyngeal anesthesia:
- 10% lidocaine (lignocaine) spray applied to the posterior pharynx
- Reduces the gag reflex and improves patient tolerance
- May allow procedure without sedation in some patients

Monitoring during sedation:
- Continuous pulse oximetry
- Blood pressure monitoring (every 5 minutes)
- Cardiac rhythm monitoring (ECG)
- Respiratory rate observation
- Supplemental oxygen is routinely provided via nasal cannula

Unsedated transnasal endoscopy:
- A small-caliber endoscope (5-6 mm) is passed through the most patent nostril after application of lidocaine gel and a nasal decongestant
- Eliminates risks of sedation; useful in outpatient or resource-limited settings''')

# ============================================================
# SECTION 6: STEP-BY-STEP PROCEDURE
# ============================================================
add_heading(doc, '6. Step-by-Step Technique of Upper GI Endoscopy', 1)

add_heading(doc, '6.1 Positioning and Setup', 2)
add_para(doc, '''
1. The patient is positioned in the left lateral decubitus (left lateral) position with the head slightly flexed forward. This position reduces aspiration risk and facilitates scope passage.
2. A bite guard (mouthpiece) is placed between the teeth to protect the endoscope and prevent the patient from biting.
3. Dentures are removed if present.
4. Intravenous access is established; sedation is administered with continuous monitoring.
5. Supplemental oxygen is provided via nasal cannula.
6. The endoscopist holds the endoscope control head in the left hand. The up-down angulation knob is operated by the left thumb; air/water/suction buttons by the left index and middle fingers. The right hand grasps the insertion tube for advancement, withdrawal, and rotation.
''')

add_heading(doc, '6.2 Esophageal Intubation', 2)
add_para(doc, '''The safest method of introducing the endoscope into the esophagus is under direct vision:

1. The scope is gently advanced over the tongue with the patient's mouth open.
2. The epiglottis and vocal cords are visualized. The tip is directed posteriorly, between the arytenoid cartilages.
3. The patient is asked to swallow. Gentle forward pressure advances the scope through the cricopharyngeal sphincter (upper esophageal sphincter) into the esophageal introitus.
4. If the tip enters the piriform sinus, it is withdrawn, repositioned in the midline, and the swallow maneuver is repeated.
5. Air is insufflated once inside the esophagus to open the lumen and improve visualization.
6. Avoid blind advancement - always advance under direct vision of the lumen.''')

add_heading(doc, '6.3 Examination of the Esophagus', 2)
add_para(doc, '''Once the esophageal lumen is visualized:
1. The scope is advanced carefully, always following the lumen.
2. A long view of the entire esophageal mucosa is obtained while withdrawing.
3. Peristaltic contractions are noted.
4. Mucosal color, texture, and vascular pattern are examined:
   - Normal: pale pink, smooth squamous epithelium
   - Look for: inflammation (esophagitis), erosions, Barrett epithelium (salmon-pink columnar mucosa replacing squamous), varices, rings (Schatzki ring), webs, strictures, or masses
5. The Z-line (squamocolumnar junction) is identified and its position relative to the GE junction is noted. The distance from the incisors is recorded (normally ~38-40 cm).
6. The lower esophageal sphincter (LES) and diaphragmatic hiatus are assessed. A hiatal hernia appears as saccular gastric mucosa above the diaphragmatic pinch.''')

add_heading(doc, '6.4 Entry into the Stomach', 2)
add_para(doc, '''1. The scope is advanced through the LES into the stomach without delay, initially to check for retained food (which risks aspiration).
2. Air is insufflated to fully distend the stomach and unfold the mucosa.
3. Orientation is established: posterior wall at 3 o'clock, lesser curvature at 12 o'clock, anterior wall at 9 o'clock, greater curvature at 6 o'clock.
4. The large rugal folds on the greater curvature of the body are noted.''')

add_heading(doc, '6.5 Examination of the Stomach', 2)
add_para(doc, '''Systematic examination of the stomach involves:

Gastric body:
- Small movements of the control knobs direct the tip in all desired directions
- Look for: ulcers, gastritis (redness, erosions), vascular lesions (angiodysplasia), neoplasia, extrinsic impressions (e.g., pancreatic pseudocyst causes posterior wall impression at 3 o'clock)

Antrum:
- The scope is advanced along the lesser curvature toward the antrum
- Rugal folds disappear as the antrum is entered
- The incisura angularis appears as a smooth arch at 12 o'clock
- Look for: gastric ulcers (most common at the incisura), antral gastritis, H. pylori-associated nodular gastritis, polyps, or mass lesions

Gastric retroflexion (J-maneuver):
- The tip is maximally angulated upward (retroflex) while positioned at the gastric angle with a small turn to the left
- This provides a view of the gastric cardia, fundus, and the lesser curvature from below - areas invisible to forward-viewing
- The scope shaft is rotated to systematically examine the cardia and fundus
- This step is essential and must not be omitted

Pylorus:
- The tip of the scope is elevated to advance toward the pyloric channel
- The pylorus is normally round; irregularities suggest previous or active ulceration
- Small circular motions reveal the entire antrum and pylorus
- Gentle pressure with slight air insufflation passes the scope through the pylorus into the duodenal bulb''')

add_heading(doc, '6.6 Examination of the Duodenum', 2)
add_para(doc, '''Duodenal bulb (D1):
- No folds; smooth-walled bulbar mucosa
- Small motions of the tip reveal the anterior and posterior recesses where ulcers may hide
- Look for: duodenitis, ulcers (commonly on the anterior wall)

Descending duodenum (D2):
- Entry into D2 usually requires a non-direct-vision maneuver: the tip is turned to the right, the shaft is rotated rightward, the tip first moves upward then downward (this turns the instrument posteriorly then down)
- Gentle withdrawal while torquing right produces a paradoxical forward movement into D2
- Plicae circulares (circular folds) are now visible
- The Ampulla of Vater is seen in profile at the 9 o'clock position on the medial duodenal wall
- Once in D2, the scope is pulled back and straightened to reduce looping - this often advances the tip further (paradoxical advancement)
- Biopsies of the duodenal mucosa are obtained here for celiac disease assessment (multiple biopsies from D1 and D2 are required - at least 4-6 specimens)

Scope withdrawal and second inspection:
- A careful, systematic withdrawal is performed
- The mucosa of the entire tract is re-inspected during withdrawal
- Biopsies, cytology brushings, and therapeutic procedures are performed as required''')

# ============================================================
# SECTION 7: SPECIAL TECHNIQUES AND ACCESSORIES
# ============================================================
add_heading(doc, '7. Special Techniques and Accessory Devices', 1)

add_heading(doc, '7.1 Tissue Acquisition', 2)
add_para(doc, '''Biopsy forceps:
- Standard biopsy forceps are passed through the working channel to obtain mucosal specimens for histology or culture
- A 2.8 mm biopsy channel accepts forceps with an 8 mm span, yielding full-thickness mucosal samples
- Large-capacity forceps provide larger specimens with less crush artifact
- Disposable forceps are now the standard of care
- "Jumbo" biopsy forceps (requiring a 3.2 mm channel) and "pediatric" forceps (for 2 mm channels in transnasal endoscopes) are available
- Multiple biopsies are recommended for malignancy detection; care must be taken near potentially resectable lesions to avoid fibrosis

Cytology brush:
- Passed through the working channel over a suspicious stricture or lesion
- Provides samples for cytological evaluation - particularly useful in strictures where forceps cannot be positioned

Endoscopic mucosal resection (EMR):
- Lifting agents (saline, hyaluronic acid) are injected into the submucosa to elevate the lesion
- The mucosa is then resected with a snare
- "Cold EMR" (without electrocautery) reduces risks of delayed bleeding and perforation
- Used for Barrett esophagus, flat polyps, early carcinoma

Endoscopic submucosal dissection (ESD):
- En bloc resection of early mucosal lesions with clear margins
- Submucosal injection elevates the lesion; mucosal incision is followed by submucosal dissection using specialized electrosurgical knives
- Standard of care for early upper GI malignancies in Japan and many Asian centers''')

add_heading(doc, '7.2 Advanced Imaging Techniques', 2)
add_para(doc, '''Chromoendoscopy:
- Topical dyes (Lugol iodine for squamous epithelium, indigo carmine, acetic acid, methylene blue) are sprayed onto the mucosa via a spray catheter
- Enhances visualization of subtle mucosal abnormalities

Narrow Band Imaging (NBI):
- Uses filtered light (blue 415 nm, green 540 nm) to enhance mucosal capillary patterns and pit architecture without dyes
- Widely used for differentiating Barrett esophagus metaplasia vs. neoplasia, and for gastric mucosal assessment

Confocal Laser Endomicroscopy (CLE):
- Probe placed through the endoscope working channel
- Provides real-time high-magnification (up to 1000x) in vivo histological images of mucosal cells to a depth of 1-2 mm
- Useful for real-time diagnosis of Barrett esophagus dysplasia, H. pylori detection in gastric mucosa, and duodenal villous architecture

Volumetric Laser Endomicroscopy (VLE):
- Uses infrared-based Fourier domain optical coherence tomography
- Imaging depth of 2-5 mm allowing visualization of the submucosa
- Differentiates squamous from columnar epithelium; evaluates Barrett esophagus in microscopic detail

Autofluorescence Imaging (AFI):
- Detects endogenous fluorophores in the mucosa
- Neoplastic tissue appears magenta/purple against a green normal mucosal background

Artificial Intelligence (AI)-assisted endoscopy:
- Deep learning neural networks trained on large endoscopic image datasets
- Can detect subtle neoplastic lesions (Barrett-associated neoplasia, early gastric cancer) with high accuracy comparable to experienced endoscopists''')

# ============================================================
# SECTION 8: NORMAL ENDOSCOPIC FINDINGS
# ============================================================
add_heading(doc, '8. Normal Endoscopic Findings', 1)

add_para(doc, 'A systematic description of normal appearances at each anatomical location:')

add_heading(doc, '8.1 Normal Esophagus', 2)
add_para(doc, '''- Mucosa: pale pink, glistening, smooth squamous epithelium
- Peristalsis: regular, well-coordinated contractions
- Caliber: uniform, ~2 cm diameter; collapses with suction
- Z-line: regular, sharply demarcated irregular border between squamous (pale) and columnar (orange-red) epithelium, at 38-40 cm from incisors
- Lower esophageal sphincter (LES): closed at rest; opens with swallowing; located at the level of the diaphragm
- Palisading vessels: visible fine longitudinal vessels at the distal esophagus, marking the end of the squamous mucosa''')

add_heading(doc, '8.2 Normal Stomach', 2)
add_para(doc, '''- Fundus: smooth, red-orange mucosa; may contain pooled gastric juice
- Body: prominent rugal folds on the greater curvature; smooth on the lesser curvature; mucosa is orange-red
- Antrum: smooth, featureless mucosa without rugal folds; orange-pink color; antral peristalsis visible
- Pylorus: round, symmetrical, rhythmically opening and closing
- Incisura angularis: smooth, curved notch at the junction of body and antrum on lesser curvature
- Gastric lake: small pool of clear mucus and secretions normally present in the fundus''')

add_heading(doc, '8.3 Normal Duodenum', 2)
add_para(doc, '''- Duodenal bulb: smooth, pale pink mucosa without folds; small amount of bile staining is normal
- Descending duodenum (D2): prominent circular plicae (valvulae conniventes); villi give a fine granular or velvety texture
- Ampulla of Vater: small papillary protrusion on the medial wall of D2 at 9 o'clock; may have a slight mucosal hood
- Color: pale pink to yellowish due to bile''')

# ============================================================
# SECTION 9: PATHOLOGICAL FINDINGS AND DIAGNOSES
# ============================================================
add_heading(doc, '9. Pathological Findings and Key Diagnoses', 1)

add_heading(doc, '9.1 Esophageal Pathology', 2)

add_heading(doc, '9.1.1 Esophagitis', 3)
add_para(doc, '''Reflux Esophagitis (GERD-related):
- Caused by chronic acid reflux injuring the squamous mucosa
- Endoscopic findings: erythema, edema, friability, linear erosions, and ulcerations at the GE junction; classified by the Los Angeles (LA) classification:
  - Grade A: one or more mucosal breaks ≤5 mm
  - Grade B: one or more mucosal breaks >5 mm, not extending between adjacent mucosal folds
  - Grade C: mucosal breaks extending between two or more adjacent folds, involving <75% of the circumference
  - Grade D: mucosal breaks involving ≥75% of the esophageal circumference
- Biopsies confirm histological esophagitis and rule out Barrett esophagus or eosinophilic esophagitis

Eosinophilic Esophagitis (EoE):
- Immune-mediated condition
- Endoscopic findings: esophageal rings (trachealization / feline esophagus), white exudates (eosinophilic microabscesses), linear furrows, reduced mucosal compliance, narrowing of the esophageal lumen
- Diagnosis requires biopsies showing >15 eosinophils per high-power field

Infectious Esophagitis:
- Candida: whitish plaques adherent to the mucosa; plaques cannot be washed off (unlike food residue)
- Herpes simplex (HSV): well-circumscribed, punched-out ulcers in the mid-esophagus
- Cytomegalovirus (CMV): large, shallow, serpiginous ulcers, often in immunocompromised patients
- Pill esophagitis: discrete ulcerations at areas of luminal narrowing (aortic arch, left mainstem bronchus level)''')

add_heading(doc, '9.1.2 Barrett Esophagus', 3)
add_para(doc, '''Barrett esophagus (BE) is a premalignant condition in which the normal stratified squamous epithelium of the esophagus is replaced by metaplastic columnar (intestinal) epithelium - a process called intestinal metaplasia (IM).

Endoscopic findings:
- Salmon-pink or orange tongues or circumferential extensions of columnar mucosa above the GE junction, replacing normal pale-pink squamous epithelium
- The Z-line is irregular and displaced proximally
- The Prague C&M classification is used to document BE:
  - C (circumferential extent): length of circumferential columnar-lined epithelium in cm
  - M (maximum extent): maximum length of any columnar tongue in cm (e.g., C3M5 = 3 cm circumferential + 5 cm maximum tongue)

Dysplasia grading (requires biopsy per Seattle protocol - 4-quadrant biopsies every 1-2 cm):
- Non-dysplastic BE (NDBE): intestinal metaplasia without dysplasia
- Low-grade dysplasia (LGD): cytological abnormalities confined to the basal layer
- High-grade dysplasia (HGD): full-thickness cytological changes; risk of progression to adenocarcinoma is 6-19% per year
- Intramucosal carcinoma: invasion into the lamina propria or muscularis mucosae

Management: surveillance endoscopy, ablative therapies (radiofrequency ablation - RFA; argon plasma coagulation - APC; cryotherapy), endoscopic mucosal resection (EMR) for nodular lesions''')

add_heading(doc, '9.1.3 Esophageal Strictures', 3)
add_para(doc, '''Benign strictures:
- Peptic stricture (most common): fixed, smooth, circumferential narrowing at the GE junction; due to chronic acid reflux and fibrosis
- Schatzki ring: a thin, web-like mucosal ring at the squamocolumnar junction; often asymptomatic but may cause intermittent dysphagia for solids
- Esophageal web: eccentric, thin membrane in the upper esophagus; associated with iron deficiency anemia (Plummer-Vinson / Paterson-Brown-Kelly syndrome)
- Anastomotic stricture: post-surgical narrowing
- Eosinophilic strictures

Malignant strictures:
- Irregular, nodular, friable narrowing with mucosal destruction
- Commonly from squamous cell carcinoma (mid-esophagus) or adenocarcinoma (GE junction)
- Biopsies are essential; endoscopic ultrasound (EUS) for staging

Management: stricture dilation (bougie or hydrostatic balloon dilation through the scope - "TTS" balloon), stent placement for malignant obstruction''')

add_heading(doc, '9.1.4 Esophageal Varices', 3)
add_para(doc, '''- Dilated submucosal veins in the distal esophagus; result from portal hypertension (typically due to liver cirrhosis)
- Endoscopic findings: blue-tinged, tortuous, longitudinal columns of dilated veins in the lower esophagus
- Graded by size:
  - Grade I: small (<5 mm), flat, not obstructing the lumen
  - Grade II: medium (5-10 mm), tortuous, occupying less than 1/3 of the lumen
  - Grade III: large (>10 mm), coiled, occupying more than 1/3 of the lumen
- Red wale signs (red streaks or spots on varices) indicate high risk of imminent bleeding
- Treatment: acute bleeding treated with rubber band ligation (RBL) or injection sclerotherapy; prophylactic ligation for large varices

Gastric varices:
- At the cardia / fundus; detected on retroflexion
- Classified by Sarin classification (GOV1: continuous with esophageal varices along lesser curvature; GOV2: continuous along greater curvature; IGV1: isolated fundal varices; IGV2: isolated elsewhere)''')

add_heading(doc, '9.1.5 Esophageal Cancer', 3)
add_para(doc, '''Squamous cell carcinoma (SCC):
- Mid-esophagus most common; associated with smoking, alcohol, achalasia, caustic strictures
- Endoscopic appearance: irregular mucosal nodularity, ulceration, or obstructing mass; may appear as superficial flat lesion in early stages

Adenocarcinoma:
- GE junction and cardia; typically arises from Barrett esophagus
- Endoscopic appearance: ulcerated, nodular mass at the lower esophagus / GE junction; may arise within visible Barrett segment
- EUS for locoregional staging; CT for metastasis assessment
- Biopsies mandatory; EMR or ESD for T1a disease

Achalasia:
- Failure of LES relaxation with esophageal dysmotility
- Endoscopic findings: dilated esophagus with retained food/liquid, absence of peristalsis, resistance at the GEJ ("tight LES"); scope passes through with gentle pressure (distinguishes from malignant obstruction)''')

add_heading(doc, '9.2 Gastric Pathology', 2)

add_heading(doc, '9.2.1 Gastritis', 3)
add_para(doc, '''Acute gastritis:
- Endoscopic findings: mucosal hyperemia (redness), edema, erosions (superficial mucosal breaks not extending through the muscularis mucosae), petechiae
- Causes: NSAIDs, alcohol, H. pylori, stress, critical illness

Helicobacter pylori gastritis:
- The most common cause of chronic gastritis worldwide
- Distribution: antrum-predominant initially; pan-gastritis with long-standing infection
- Endoscopic findings: nodular antral mucosa ("cobblestone" or "chicken skin" appearance), redness, erosions, atrophy
- Diagnosis: biopsy for CLO (Campylobacter-like organism) rapid urease test, histology (modified Giemsa or Warthin-Starry stain), culture, or stool antigen test
- Sydney system biopsies: 5 specimens (2 antrum, 2 body, 1 incisura) for proper assessment

Atrophic gastritis and intestinal metaplasia:
- Loss of gastric glands; pale, thinned mucosa with visible submucosal vessels
- Intestinal metaplasia: replacement of gastric columnar epithelium with intestinal-type epithelium; premalignant
- Classified as complete (type I) or incomplete (types II/III; higher cancer risk)

Autoimmune gastritis (Type A):
- Affects the body and fundus (corpus-predominant)
- Associated with anti-parietal cell and anti-intrinsic factor antibodies; leads to pernicious anemia
- Endoscopic findings: mucosal atrophy in the body/fundus; prominent vascular pattern; may develop enterochromaffin-like (ECL) cell carcinoids
- Spares the antrum (in contrast to H. pylori gastritis)''')

add_heading(doc, '9.2.2 Peptic Ulcer Disease', 3)
add_para(doc, '''A peptic ulcer is a full-thickness mucosal defect extending through the muscularis mucosae, most commonly caused by H. pylori infection or NSAID use.

Gastric ulcers:
- Most common on the lesser curvature, particularly at the incisura angularis
- Endoscopic appearance: circular or oval mucosal defect with a white fibrinous base; raised, reddened, edematous edges
- Benign ulcers: regular, smooth edges; radiating mucosal folds
- Malignant ulcers: irregular, heaped-up nodular edges; mucosal destruction
- Biopsies (minimum 6-8 specimens from margins and base) are mandatory for all gastric ulcers to exclude malignancy
- Forrest classification for bleeding peptic ulcers:
  - Ia: Spurting arterial bleeding
  - Ib: Oozing active bleeding
  - IIa: Non-bleeding visible vessel
  - IIb: Adherent clot
  - IIc: Flat pigmented spot
  - III: Clean-based ulcer (no stigmata of bleeding)

Duodenal ulcers:
- Most commonly on the anterior wall of the duodenal bulb
- Usually benign (duodenal ulcers are rarely malignant)
- Biopsy not routinely required unless an unusual location or appearance
- Complications: perforation (anterior ulcers into peritoneal cavity) and bleeding (posterior ulcers erode the gastroduodenal artery)''')

add_heading(doc, '9.2.3 Gastric Polyps', 3)
add_para(doc, '''Types:
- Fundic gland polyps (most common): small (<1 cm), sessile, pale; body/fundus; benign; associated with long-term PPI use and FAP
- Hyperplastic polyps: associated with chronic H. pylori gastritis or atrophic gastritis; may become dysplastic if >2 cm; biopsied and removed if large
- Adenomatous polyps (gastric adenoma): flat or slightly elevated; associated with intestinal metaplasia; premalignant; require complete removal
- Subepithelial lesions: gastrointestinal stromal tumors (GISTs), leiomyomas, lipomas, carcinoids - assessed by EUS for size, layer of origin, and echogenicity''')

add_heading(doc, '9.2.4 Gastric Cancer', 3)
add_para(doc, '''- Second most common cause of cancer death worldwide
- Most are adenocarcinomas; less common types include lymphoma, GIST, carcinoid
- Endoscopic classification (Borrmann):
  - Type I: polypoid, well-defined
  - Type II: ulcerated with raised margins
  - Type III: ulcerated with infiltrative margins
  - Type IV: diffusely infiltrating (linitis plastica - rigid, non-distensible stomach)
- Early gastric cancer (EGC): confined to mucosa/submucosa regardless of lymph node status; classified as Type I (elevated), IIa (slightly elevated), IIb (flat), IIc (slightly depressed), III (excavated) by the Japanese classification
- Diagnosis: biopsies from all suspicious lesions; EUS for T staging; CT for distant metastasis
- Treatment: EMR/ESD for early mucosal disease; gastrectomy for advanced cases

Mucosa-Associated Lymphoid Tissue (MALT) lymphoma:
- Low-grade B-cell lymphoma of the stomach; strongly associated with H. pylori
- Endoscopic findings: erythema, erosions, nodularity, ulceration - can mimic gastritis or peptic ulcer
- Diagnosis: biopsy (Giemsa stain for H. pylori; immunohistochemistry for lymphocyte markers)
- H. pylori eradication achieves remission in 70-90% of low-grade MALT lymphomas''')

add_heading(doc, '9.2.5 Vascular Lesions', 3)
add_para(doc, '''Angiodysplasia (gastric antral vascular ectasia - GAVE) / Watermelon stomach:
- Prominent, dilated, tortuous submucosal vessels radiating from the pylorus in a pattern resembling stripes on a watermelon
- Associated with portal hypertension, cirrhosis, systemic sclerosis
- Treated with argon plasma coagulation (APC) or laser therapy

Dieulafoy lesion:
- Abnormally large submucosal artery (caliber-persistent artery) that erodes through the mucosa without ulceration; usually in the proximal stomach
- Appears as a small mucosal defect with an exposed vessel; can cause massive hemorrhage disproportionate to its size
- Treatment: hemostatic clipping, rubber band ligation, or thermal coagulation

Gastric antral vascular ectasia (GAVE):
- "Watermelon stomach" pattern with linear red streaks in the antrum
- Treated with APC or band ligation''')

add_heading(doc, '9.3 Duodenal Pathology', 2)

add_heading(doc, '9.3.1 Duodenitis and Duodenal Ulcer', 3)
add_para(doc, '''Duodenitis:
- Mucosal erythema, erosions, and edema in the duodenal bulb
- Caused by H. pylori, NSAIDs, or Crohn disease
- Biopsies for H. pylori urease testing

Duodenal ulcers:
- Anterior wall of the duodenal bulb is the most common site
- Benign; rarely biopsied unless atypical location
- Complications: anterior ulcers perforate into the peritoneal cavity; posterior ulcers bleed from the gastroduodenal artery

Rarely: peptic ulcer in D2 should raise suspicion for Zollinger-Ellison syndrome (gastrinoma)''')

add_heading(doc, '9.3.2 Celiac Disease', 3)
add_para(doc, '''- Immune-mediated enteropathy triggered by gluten; damages duodenal and proximal jejunal villi
- Endoscopic findings: villous atrophy (flat, smooth mucosa instead of normal velvety texture), loss or scalloping of duodenal folds, mosaic pattern, and visible submucosal vascularity
- "Scalloping" of the plicae circulares and reduced fold count (<3 folds in D2) are suggestive
- Diagnosis: duodenal biopsies (at least 4-6 specimens from D2 and D1); Marsh classification for histological staging
- Serology: anti-tissue transglutaminase IgA (anti-tTG IgA) and endomysial antibodies (EMA)''')

add_heading(doc, '9.3.3 Ampullary Pathology', 3)
add_para(doc, '''- Ampullary adenoma: protuberant lesion at the Ampulla of Vater; may cause bile duct obstruction (jaundice, cholangitis); associated with FAP
- Ampullary carcinoma: obstructing, friable mass at the ampulla; may cause painless jaundice
- Side-viewing duodenoscope provides optimal visualization; biopsies and EUS for staging

Periampullary diverticulum:
- Common incidental finding; does not usually require treatment but may complicate ERCP''')

add_heading(doc, '9.3.4 Duodenal Tumors', 3)
add_para(doc, '''- Carcinoid tumors (neuroendocrine tumors): yellow-pink submucosal nodules; may secrete hormones
- Brunner gland hamartomas: nodular or polypoid lesions in the bulb; usually benign
- Lymphoma: diffuse infiltration causing thickened folds, nodularity, or ulceration
- Adenocarcinoma: rare; obstructing, ulcerated mass in D2-D3
- Metastatic disease: Kaposi sarcoma (HIV), melanoma, breast cancer can metastasize to the duodenum''')

# ============================================================
# SECTION 10: THERAPEUTIC INTERVENTIONS
# ============================================================
add_heading(doc, '10. Therapeutic Endoscopic Interventions', 1)

add_heading(doc, '10.1 Hemostasis', 2)
add_para(doc, '''Management of upper GI bleeding is one of the most critical therapeutic applications of UGI endoscopy. Modalities include:

Injection therapy:
- Adrenaline (epinephrine) 1:10,000 solution injected in 4-quadrant pattern around a bleeding vessel using a needle catheter
- Causes vasoconstriction and tamponade; used in combination with other modalities

Thermal/Contact coagulation:
- Monopolar or bipolar electrocoagulation probes
- Argon plasma coagulation (APC): non-contact thermal energy via ionized argon gas
- Heater probe

Mechanical methods:
- Endoscopic hemoclips: small metallic clips deployed to compress a bleeding vessel; ideal for Dieulafoy lesions, post-polypectomy bleeding, and Forrest IIa/IIb ulcers
- Rubber band ligation (RBL): for variceal hemorrhage

Hemostatic sprays and powders:
- TC-325 (Hemospray): biomineral powder applied over a bleeding lesion via spray catheter; forms a coagulum
- Useful as rescue therapy for diffuse or inaccessible bleeding

Over-the-scope clips (OTSC):
- Large clips mounted on the tip of the endoscope for treating large vessels or closing defects
- Higher compression force than standard clips''')

add_heading(doc, '10.2 Dilation', 2)
add_para(doc, '''Stricture dilation for benign or malignant esophageal, anastomotic, or pyloric strictures:
- Bougie dilators (Savary-Gilliard, Maloney): solid tapered dilators passed over a guidewire under fluoroscopic guidance
- Hydrostatic balloon dilators (TTS - through-the-scope): inflated under endoscopic and/or fluoroscopic vision; used for pyloric and anastomotic strictures
- Rule of three: no more than three consecutive dilator sizes (3 mm increments) per session to avoid perforation''')

add_heading(doc, '10.3 Variceal Treatment', 2)
add_para(doc, '''Rubber band ligation (RBL):
- Gold standard for esophageal variceal hemorrhage and prophylaxis
- Bands are deployed at the base of each varix, causing ischemic necrosis and obliteration

Injection sclerotherapy:
- Sclerosant (ethanolamine, sodium tetradecyl sulfate) injected into or adjacent to the varix
- Higher complication rate than RBL; used when banding is not feasible

Cyanoacrylate glue injection:
- N-butyl-2-cyanoacrylate injected directly into gastric varices where banding is not effective
- Immediate hemostasis through polymerization (hardening) on contact with blood''')

add_heading(doc, '10.4 Endoscopic Mucosal Resection (EMR) and ESD', 2)
add_para(doc, '''EMR: Used for flat or sessile polyps, Barrett-related neoplasia, and early mucosal cancers up to 2 cm
ESD: Enables en bloc resection of larger lesions (>2 cm) with free margins; preferred for early gastric cancer in Asian centers; technically demanding; higher complication rate (perforation, bleeding)''')

add_heading(doc, '10.5 Stent Placement', 2)
add_para(doc, '''Self-expanding metal stents (SEMS):
- Placed over a guidewire through the working channel under fluoroscopic and endoscopic guidance
- Indications: malignant esophageal, gastric outlet, and duodenal obstruction
- Covered vs. uncovered: fully covered stents prevent tumor ingrowth and allow removal; uncovered stents anchor better
- Duodenal stents: highly effective for malignant gastric outlet obstruction (pancreatic cancer)

EUS-guided gastroenterostomy (EUS-GE):
- Lumen-apposing metal stents (LAMS) create a bypass between stomach and distal duodenum/jejunum
- Emerging technique for benign and malignant gastric outlet obstruction''')

add_heading(doc, '10.6 Percutaneous Endoscopic Gastrostomy (PEG)', 2)
add_para(doc, '''- Endoscopic placement of a feeding tube through the anterior abdominal wall directly into the stomach
- Indications: neurological dysphagia, head and neck cancer, prolonged mechanical ventilation
- Technique: endoscopic transillumination identifies the optimal stomach wall site; a needle is inserted percutaneously and the tube is pulled through into place ("pull technique")''')

add_heading(doc, '10.7 Radiofrequency Ablation (RFA)', 2)
add_para(doc, '''- Used for ablation of Barrett esophagus (dysplastic and non-dysplastic)
- A balloon-based electrode (HALO360) or focal electrode (HALO90) delivers controlled radiofrequency energy to ablate the columnar epithelium
- Re-epithelialization with normal squamous epithelium follows
- Effective for eradicating dysplasia and reducing progression to adenocarcinoma''')

# ============================================================
# SECTION 11: COMPLICATIONS
# ============================================================
add_heading(doc, '11. Complications of Upper GI Endoscopy', 1)

add_para(doc, 'UGI endoscopy is generally very safe. The overall complication rate is <0.1% for diagnostic procedures and 1-3% for therapeutic procedures. Major complications include:')

add_heading(doc, '11.1 Perforation', 2)
add_para(doc, '''- Most feared complication; incidence ~0.01-0.04% for diagnostic EGD; higher for therapeutic (dilation: 0.5-2%; ESD: 1-10%)
- Sites: posterior pharynx (Zenker diverticulum), cervical esophagus (cricopharyngeal muscle), stricture areas
- Presentation: neck/chest/abdominal pain, subcutaneous emphysema, pneumomediastinum on imaging
- Management: conservative (nil by mouth, antibiotics, NGT) for small contained tears; surgical or endoscopic closure for large perforations''')

add_heading(doc, '11.2 Hemorrhage', 2)
add_para(doc, '''- Diagnostic EGD: extremely rare bleeding from biopsy (<0.01%)
- Therapeutic procedures (EMR, ESD, polypectomy): higher risk (1-2%)
- Management: endoscopic hemostasis (clips, thermal, injection)''')

add_heading(doc, '11.3 Aspiration', 2)
add_para(doc, '''- Aspiration of gastric contents during endoscopy; risk increased in emergency procedures, inadequate fasting, or poor sedation
- Prevention: adequate pre-procedural fasting, left lateral positioning, IV erythromycin in UGI bleeders to accelerate gastric emptying''')

add_heading(doc, '11.4 Sedation-Related Complications', 2)
add_para(doc, '''- Respiratory depression, hypoxemia, hypotension, paradoxical agitation
- Reversal agents: flumazenil for benzodiazepines; naloxone for opioids
- Prevention: appropriate patient selection, careful titration, continuous monitoring, oxygen supplementation''')

add_heading(doc, '11.5 Infection', 2)
add_para(doc, '''- Bacteremia: transient but rarely clinically significant; antibiotic prophylaxis not routinely indicated
- PEG site infection: most common infectious complication of therapeutic endoscopy; prevented by peri-procedural antibiotics
- Endoscope reprocessing: high-level disinfection protocols (Cidex, peracetic acid) are mandatory to prevent cross-infection''')

# ============================================================
# SECTION 12: POST-PROCEDURE
# ============================================================
add_heading(doc, '12. Post-Procedure Care and Reporting', 1)

add_heading(doc, '12.1 Recovery', 2)
add_para(doc, '''- Patient is observed in the recovery area until sedation has fully resolved
- Vital signs monitored: blood pressure, pulse oximetry, heart rate
- Patients sedated with IV medications must not drive for 24 hours
- Mild throat soreness, bloating, and burping are common and expected; resolve within a few hours
- Patients with abnormal findings requiring biopsies are advised to await results before recommencing anticoagulant therapy (if withheld)
- Specific post-procedure instructions vary by intervention performed (e.g., soft diet after dilation; nil by mouth after PEG for several hours)''')

add_heading(doc, '12.2 Endoscopy Reporting', 2)
add_para(doc, '''A complete endoscopy report should include:
- Patient demographics, indication, date, and endoscopist details
- Scope type used and withdrawal time
- Scope insertion route (oral vs. transnasal)
- Sedation details (type, dose, monitoring)
- Quality indicators: adequacy of preparation, visualization quality, sites inspected, retroflexion performed or not
- All anatomical segments examined and their appearance
- Mucosal abnormalities: precise location (distance from incisors or pylorus), size, morphology, number
- Biopsies: site, number, labeling, and whether specimens are sent for histology, CLO test, cytology, or culture
- Therapeutic interventions performed
- Immediate complications
- Follow-up plan and histology result pending''')

# ============================================================
# SECTION 13: QUALITY INDICATORS
# ============================================================
add_heading(doc, '13. Quality Indicators in UGI Endoscopy', 1)

add_para(doc, 'High-quality upper endoscopy is defined by adherence to recognized performance benchmarks:')
add_bullet(doc, 'Adequate preparation: stomach must be free of significant retained food or liquid')
add_bullet(doc, 'Complete examination: esophagus, all gastric regions (including cardia/fundus on retroflexion), duodenal bulb, and D2 must all be examined')
add_bullet(doc, 'Documentation of retroflexion: gastric retroflexion (J-maneuver) is mandatory for complete fundal and cardia assessment')
add_bullet(doc, 'Minimum inspection time: adequate withdrawal time for systematic inspection')
add_bullet(doc, 'Sydney protocol biopsy compliance: 5 biopsies (2 antrum, 2 body, 1 incisura) for H. pylori assessment and atrophy/metaplasia staging')
add_bullet(doc, 'Barrett esophagus biopsies: Seattle protocol (4-quadrant biopsies every 1-2 cm with targeted biopsies of visible lesions)')
add_bullet(doc, 'Proper documentation and reporting of all findings')
add_bullet(doc, 'Complication tracking: perforation rate <0.01% for diagnostic EGD')

# ============================================================
# SECTION 14: SPECIAL POPULATIONS
# ============================================================
add_heading(doc, '14. UGI Endoscopy in Special Populations', 1)

add_heading(doc, '14.1 Pregnancy', 2)
add_para(doc, '''Endoscopy is generally deferred in pregnancy unless urgently indicated (active bleeding, severe dysphagia, foreign body). When required:
- Second trimester is the safest period
- Left lateral decubitus positioning to avoid aortocaval compression
- Minimize sedation; consult obstetrics for medication safety
- Fetal monitoring during and after the procedure''')

add_heading(doc, '14.2 Anticoagulated Patients', 2)
add_para(doc, '''- BSG/ESGE 2021 guidelines stratify procedures by bleeding risk (high vs. low) and anticoagulant/antiplatelet therapy
- Low-risk procedures (diagnostic EGD, biopsy): aspirin and P2Y12 inhibitors can usually be continued; DOACs require a brief hold
- High-risk procedures (EMR, ESD, dilation, PEG): DOACs withheld for 24-48 hours; warfarin withheld with INR check; heparin bridging for high-risk atrial fibrillation or mechanical heart valves''')

add_heading(doc, '14.3 Pediatrics', 2)
add_para(doc, '''- Smaller diameter endoscopes or "pediatric" gastroscopes are used
- General anesthesia is more commonly required
- Indications include: recurrent vomiting, failure to thrive, foreign body ingestion, UGI bleeding, suspected celiac disease, eosinophilic esophagitis''')

# ============================================================
# SECTION 15: CONCLUSION
# ============================================================
add_heading(doc, '15. Summary', 1)
add_para(doc, '''Upper gastrointestinal endoscopy is an indispensable tool in modern gastroenterology and surgery. Its ability to directly visualize the mucosa of the esophagus, stomach, and duodenum - combined with the capacity to obtain tissue biopsies, perform hemostasis, dilate strictures, resect mucosal lesions, and ablate premalignant tissue - makes it both the most sensitive diagnostic modality and the first-line therapeutic tool for a wide array of upper GI conditions.

Understanding the anatomy from the cricopharyngeal muscle to the descending duodenum, mastering the technical steps of scope insertion and systematic examination (including the mandatory gastric retroflexion), recognizing normal and abnormal mucosal appearances, and knowing when and how to apply therapeutic interventions are the foundations of competent practice.

When performed with appropriate pre-procedural preparation, sedation, and monitoring; guided by evidence-based indications; and reported in accordance with quality standards, upper GI endoscopy carries an excellent safety profile with a transformative impact on patient outcomes across conditions ranging from peptic ulcer disease and H. pylori gastritis to Barrett esophagus, early gastric cancer, and portal hypertensive bleeding.''')

# ============================================================
# REFERENCES
# ============================================================
add_heading(doc, 'Key References', 1)
refs = [
    "Fischer JE et al. Fischer's Mastery of Surgery, 8th Edition. Chapter 19: Technique of Esophagogastroduodenoscopy. Wolters Kluwer / Lippincott Williams & Wilkins.",
    "Yamada T et al. Yamada's Textbook of Gastroenterology, 7th Edition. Chapter 118: Upper Gastrointestinal Endoscopy. Wiley-Blackwell.",
    "Bailey H, Love R. Bailey and Love's Short Practice of Surgery, 28th Edition. Chapter 9: Gastrointestinal Endoscopy. CRC Press / Taylor & Francis.",
    "Barash PG et al. Barash, Cullen, and Stoelting's Clinical Anesthesia, 9th Edition. Chapter on Upper Gastrointestinal Endoscopy. Wolters Kluwer.",
    "American Society for Gastrointestinal Endoscopy (ASGE). Preprocedural laboratory testing guidelines.",
    "Sharma P, Shaheen NJ, Katzka D et al. AGA Clinical Practice Guidelines on Barrett's Esophagus. Gastroenterology, 2023.",
    "Bisschops R et al. European Society of Gastrointestinal Endoscopy (ESGE) quality performance measures for upper gastrointestinal endoscopy. Endoscopy, 2016.",
    "Pimentel-Nunes P et al. ESGE guidelines on endoscopic submucosal dissection for superficial gastrointestinal neoplasia. Endoscopy, 2022.",
]
for i, ref in enumerate(refs, 1):
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(4)
    run = p.add_run(f'{i}. {ref}')
    run.font.size = Pt(10)

# Save the document
output_path = '/tmp/workspace/ugi-scopy/UGI_Scopy_Comprehensive_Essay.docx'
doc.save(output_path)
print(f"Document saved to: {output_path}")
Running Command

cd /tmp/workspace/ugi-scopy && python3 create_ugiscopy_doc.py

Running Command

python3 -c " from docx import Document doc = Document('/tmp/workspace/ugi-scopy/UGI_Scopy_Comprehensive_Essay.docx') headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')] print(f'Total paragraphs: {len(doc.paragraphs)}') print(f'Total headings: {len(headings)}') print('Headings:') for h in headings: print(' -', h) "

Your Word document is ready for download:

UGI Scopy Comprehensive Essay

Word Document · DOCX


Here is what the document covers across 15 numbered sections (196 paragraphs, 68 headings):
1. Introduction - History from Bozzini's 1806 Lichtleiter to modern video CCD endoscopes; Rudolf Schindler's role; Basil Hirschowitz's fiberoptic revolution.
2. Anatomy of the UGI Tract
  • Esophagus: UES to LES, wall layers, Z-line at 38-40 cm, palisading vessels
  • Stomach: Cardia, fundus, body, antrum, pylorus, incisura angularis, curvatures; endoscopic clock orientation
  • Duodenum: D1 (bulb) through D4, Ampulla of Vater, plicae circulares
3. Equipment - CCD endoscope components, control head mechanics, specialized scopes (side-viewer, enteroscope, transnasal, NBI)
4. Indications and Contraindications - Full diagnostic and therapeutic indication lists; absolute and relative contraindications
5. Pre-Procedure Preparation - Fasting protocols, medication review, consent, selective laboratory testing (ASGE guidelines), sedation options (midazolam/fentanyl, propofol, topical lidocaine, transnasal unsedated)
6. Step-by-Step Technique - Patient positioning, esophageal intubation under direct vision, esophageal inspection, stomach entry, gastric examination with retroflexion (J-maneuver), duodenal bulb and D2 examination
7. Special Techniques - Biopsy forceps, cytology brush, EMR, ESD, chromoendoscopy, NBI, confocal laser endomicroscopy, VLE, AI-assisted detection
8. Normal Endoscopic Findings - Segment-by-segment description of normal mucosa
9. Pathological Findings and Diagnoses
  • Esophageal: Reflux esophagitis (LA grading), eosinophilic esophagitis, infectious esophagitis, Barrett esophagus (Prague C&M, Seattle protocol, dysplasia grading), strictures (Schatzki ring, Plummer-Vinson), varices (grading, Sarin classification), squamous cell carcinoma, adenocarcinoma, achalasia
  • Gastric: H. pylori gastritis (Sydney protocol), autoimmune gastritis, atrophic gastritis, peptic ulcer disease (Forrest classification for bleeding), polyps (fundic gland, hyperplastic, adenoma), GIST, gastric cancer (Borrmann classification), MALT lymphoma, GAVE / Dieulafoy lesion
  • Duodenal: Duodenitis, duodenal ulcer, celiac disease (Marsh classification), ampullary adenoma/carcinoma, carcinoid tumors, lymphoma
10. Therapeutic Interventions - Hemostasis (injection, thermal, clips, hemostatic sprays, OTSC), dilation (bougie, TTS balloon, rule of three), variceal banding and sclerotherapy, cyanoacrylate for gastric varices, EMR/ESD, SEMS stenting, EUS-GE, PEG, radiofrequency ablation
11. Complications - Perforation, hemorrhage, aspiration, sedation-related events, infection - with management
12. Post-Procedure Care and Reporting - Recovery, documentation standards, quality indicators
13. Quality Indicators - Sydney protocol compliance, retroflexion documentation, Barrett biopsies, perforation benchmarks
14. Special Populations - Pregnancy, anticoagulated patients (BSG/ESGE 2021 framework), pediatrics
15. Summary + Key References - 8 authoritative sources cited (Fischer's Mastery of Surgery, Yamada's Gastroenterology, Bailey & Love, ASGE, ESGE guidelines)
This is a shared conversation. Sign in to Orris to start your own chat.