~/urinalysis-report/generate_report.py
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import copy
doc = Document()
# ─── PAGE MARGINS ────────────────────────────────────────────────────────────
section = doc.sections[0]
section.left_margin = Inches(1.25)
section.right_margin = Inches(1.25)
section.top_margin = Inches(1.0)
section.bottom_margin = Inches(1.0)
# ─── DEFAULT STYLE: Times New Roman 12pt, 1.5 line spacing, justified ────────
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
normal = doc.styles['Normal']
normal.font.name = 'Times New Roman'
normal.font.size = Pt(12)
normal.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
def set_line_spacing_15(para):
"""Apply 1.5 line spacing to a paragraph."""
from docx.shared import Pt
from docx.oxml.ns import qn
pPr = para._p.get_or_add_pPr()
spacing = OxmlElement('w:spacing')
spacing.set(qn('w:line'), '360') # 360 twips = 1.5 × 240
spacing.set(qn('w:lineRule'), 'auto')
pPr.append(spacing)
def add_heading(text, level=1):
h = doc.add_heading(text, level=level)
h.alignment = WD_ALIGN_PARAGRAPH.CENTER if level == 1 else WD_ALIGN_PARAGRAPH.LEFT
run = h.runs[0] if h.runs else h.add_run()
run.font.name = 'Times New Roman'
run.font.color.rgb = RGBColor(0, 0, 0)
if level == 1:
run.font.size = Pt(16)
run.bold = True
elif level == 2:
run.font.size = Pt(14)
run.bold = True
else:
run.font.size = Pt(12)
run.bold = True
set_line_spacing_15(h)
return h
def add_para(text, bold=False, italic=False, center=False):
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER if center else WD_ALIGN_PARAGRAPH.JUSTIFY
run = p.add_run(text)
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.bold = bold
run.italic = italic
set_line_spacing_15(p)
return p
def add_bullet(text, bold_prefix=None):
"""Add a bullet point. bold_prefix is bolded, rest is normal."""
p = doc.add_paragraph(style='List Bullet')
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
set_line_spacing_15(p)
if bold_prefix:
r1 = p.add_run(bold_prefix)
r1.font.name = 'Times New Roman'
r1.font.size = Pt(12)
r1.bold = True
r2 = p.add_run(text)
r2.font.name = 'Times New Roman'
r2.font.size = Pt(12)
else:
r = p.add_run(text)
r.font.name = 'Times New Roman'
r.font.size = Pt(12)
return p
def add_section_row(label, content):
"""Add a labeled row: LABEL (bold): content"""
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
set_line_spacing_15(p)
r1 = p.add_run(label + ": ")
r1.font.name = 'Times New Roman'
r1.font.size = Pt(12)
r1.bold = True
r2 = p.add_run(content)
r2.font.name = 'Times New Roman'
r2.font.size = Pt(12)
return p
def page_break():
doc.add_page_break()
# ════════════════════════════════════════════════════════════════════════════════
# TITLE PAGE
# ════════════════════════════════════════════════════════════════════════════════
for _ in range(5):
p = doc.add_paragraph()
set_line_spacing_15(p)
add_para("FACULTY OF HEALTH SCIENCES", bold=True, center=True)
add_para("Department of Biomedical Laboratory Science", italic=True, center=True)
doc.add_paragraph()
add_para("LAB ASSIGNMENT REPORT", bold=True, center=True)
doc.add_paragraph()
# Title
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
set_line_spacing_15(p)
r = p.add_run("URINALYSIS: CHEMICAL EXAMINATION OF URINE")
r.font.name = 'Times New Roman'
r.font.size = Pt(18)
r.bold = True
doc.add_paragraph()
add_para("(Assignment Outline: Chemical Examination of Urine — MM: 50)", italic=True, center=True)
doc.add_paragraph()
for _ in range(4):
p = doc.add_paragraph()
set_line_spacing_15(p)
add_section_row("Student Name", "______________________________")
add_section_row("Student ID", "______________________________")
add_section_row("Programme", "______________________________")
add_section_row("Course", "Urinalysis / Clinical Chemistry")
add_section_row("Instructor", "______________________________")
add_section_row("Date of Submission", "______________________________")
doc.add_paragraph()
add_section_row("Word Count", "Approx. 3,800 words | Pages: 11–12")
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# TABLE OF CONTENTS (manual)
# ════════════════════════════════════════════════════════════════════════════════
add_heading("Table of Contents", level=1)
toc_items = [
("1.", "Introduction", "3"),
("2.", "Parameter 1: Glucose", "4"),
("3.", "Parameter 2: Bilirubin", "5"),
("4.", "Parameter 3: Ketones", "5"),
("5.", "Parameter 4: Blood (Haemoglobin)", "6"),
("6.", "Parameter 5: pH", "7"),
("7.", "Parameter 6: Protein", "8"),
("8.", "Parameter 7: Urobilinogen", "9"),
("9.", "Parameter 8: Nitrite", "9"),
("10.", "Parameter 9: Leukocyte Esterase", "10"),
("11.", "Parameter 10: Specific Gravity", "11"),
("12.", "Conclusion", "12"),
("13.", "References", "12"),
]
for num, title, pg in toc_items:
p = doc.add_paragraph()
set_line_spacing_15(p)
r = p.add_run(f"{num} {title} {'.' * (55 - len(num) - len(title))} {pg}")
r.font.name = 'Times New Roman'
r.font.size = Pt(12)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# 1. INTRODUCTION
# ════════════════════════════════════════════════════════════════════════════════
add_heading("1. Introduction", level=1)
add_para(
"Urinalysis is one of the oldest and most frequently ordered diagnostic procedures in clinical medicine. "
"It involves the systematic examination of urine to detect abnormalities that may indicate disease in the "
"kidneys, urinary tract, or other organ systems. The procedure encompasses three broad components: "
"physical (gross) examination, chemical examination, and microscopic examination of urinary sediment. "
"This report focuses specifically on the chemical examination of urine, which is typically performed "
"using a multi-parameter reagent dipstick strip."
)
add_para(
"The chemical examination of urine has significant clinical utility because urine composition directly "
"reflects the metabolic state of the body. The kidneys filter approximately 180 litres of plasma per day, "
"and the resulting urine contains metabolic by-products, hormones, electrolytes, and cellular materials "
"that, when abnormal, provide critical diagnostic information. The reagent strip method evaluates ten key "
"parameters: glucose, bilirubin, ketones, blood, pH, protein, urobilinogen, nitrite, leukocyte esterase, "
"and specific gravity."
)
add_para(
"The purpose of this assignment is to describe the normal value, clinical significance, causes of abnormal "
"findings, clinical manifestations, organs affected, further investigations, and management options for "
"each of these ten urinalysis parameters. Understanding these parameters is essential for health science "
"students and practitioners to interpret urinalysis results accurately and guide patient care decisions."
)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# HELPER: standard parameter sub-headings
# ════════════════════════════════════════════════════════════════════════════════
def add_parameter(number, name, normal_value, significance, causes_high, causes_low,
clinical_manifestations, organs_affected, investigations, management):
add_heading(f"Parameter {number}: {name}", level=1)
add_section_row("Normal Value", normal_value)
doc.add_paragraph()
add_heading("Significance / Function", level=2)
for line in significance:
add_bullet(line)
add_heading("Causes of Abnormal Findings", level=2)
if causes_high:
add_para("Elevated / Positive:", bold=True)
for line in causes_high:
add_bullet(line)
if causes_low:
add_para("Decreased / Absent:", bold=True)
for line in causes_low:
add_bullet(line)
add_heading("Clinical Manifestations", level=2)
for line in clinical_manifestations:
add_bullet(line)
add_heading("Organs Affected", level=2)
for line in organs_affected:
add_bullet(line)
add_heading("Further Investigations", level=2)
for line in investigations:
add_bullet(line)
add_heading("Treatment / Management", level=2)
for line in management:
add_bullet(line)
doc.add_paragraph()
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 1: GLUCOSE
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=1, name="Glucose (Glucosuria)",
normal_value="Negative (< 0.8 mmol/L or < 15 mg/dL). Glucose is not normally detectable in urine by reagent strip.",
significance=[
"Glucose is filtered freely by the glomerulus and reabsorbed almost entirely by the proximal convoluted tubule (PCT) via sodium-glucose co-transporters (SGLT2).",
"Glucosuria indicates that the plasma glucose level has exceeded the renal threshold (~10 mmol/L or 180 mg/dL) or that tubular reabsorption is impaired.",
"The reagent strip uses glucose oxidase–peroxidase enzymatic reaction; it is specific for glucose and does not detect other reducing sugars.",
"Serves as an important screening tool for diabetes mellitus and gestational diabetes.",
],
causes_high=[
"Diabetes mellitus (Type 1 and Type 2) — most common cause; hyperglycaemia exceeds renal threshold.",
"Gestational diabetes — transient glucosuria in pregnancy.",
"Cushing's syndrome — corticosteroid-induced hyperglycaemia.",
"Acromegaly and phaeochromocytoma — secondary hyperglycaemia.",
"Renal glucosuria (benign) — normal blood glucose but impaired tubular reabsorption (Fanconi syndrome, SGLT2 mutations).",
"Acute pancreatitis, stress hyperglycaemia, parenteral nutrition.",
],
causes_low=[
"Not clinically significant; absence is normal.",
"False negative: high levels of ascorbic acid (vitamin C) can inhibit the test reaction.",
],
clinical_manifestations=[
"Polyuria, polydipsia, and polyphagia (classic triad of diabetes mellitus).",
"Unintentional weight loss, fatigue, and blurred vision.",
"Recurrent fungal or bacterial infections (especially Candida vulvovaginitis).",
"In diabetic ketoacidosis: nausea, vomiting, abdominal pain, Kussmaul breathing, altered consciousness.",
"Dehydration and electrolyte imbalances.",
],
organs_affected=[
"Pancreas (beta-cell dysfunction or destruction).",
"Kidneys (proximal tubule; glomerular filtration pressure).",
"Eyes (diabetic retinopathy), peripheral nerves (neuropathy), cardiovascular system (macrovascular complications).",
],
investigations=[
"Fasting plasma glucose (FPG): ≥ 7.0 mmol/L diagnostic for DM.",
"Random plasma glucose: ≥ 11.1 mmol/L with symptoms.",
"Oral glucose tolerance test (OGTT): 2-hour value ≥ 11.1 mmol/L.",
"HbA1c: ≥ 48 mmol/mol (6.5%) — reflects 3-month glycaemic control.",
"Urine microalbumin to assess early diabetic nephropathy.",
"C-peptide and insulin levels to differentiate Type 1 from Type 2 DM.",
],
management=[
"Type 1 DM: Insulin therapy (basal-bolus regimen), carbohydrate counting, blood glucose monitoring.",
"Type 2 DM: Lifestyle modification (diet, exercise), oral hypoglycaemics (metformin first-line), SGLT2 inhibitors, GLP-1 agonists, insulin if required.",
"Gestational diabetes: Dietary control, insulin if targets not met; avoid oral hypoglycaemics in some guidelines.",
"Regular HbA1c monitoring, foot care, ophthalmology review, and renal function surveillance.",
]
)
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 2: BILIRUBIN
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=2, name="Bilirubin (Bilirubinuria)",
normal_value="Negative. Bilirubin is not normally detectable in urine; only conjugated (direct) bilirubin appears in urine when present.",
significance=[
"Bilirubin is a yellow pigment produced from the breakdown of haem in red blood cells.",
"Unconjugated bilirubin is water-insoluble and bound to albumin — it cannot pass through the glomerulus.",
"Conjugated (direct) bilirubin is water-soluble; when elevated in blood due to hepatic or post-hepatic disease, it is filtered by the glomerulus and detected in urine.",
"Urine bilirubin is an early indicator of hepatocellular disease or biliary obstruction, often appearing before jaundice becomes clinically visible.",
],
causes_high=[
"Hepatocellular disease: viral hepatitis (A, B, C), alcoholic hepatitis, drug-induced liver injury, cirrhosis.",
"Cholestatic (obstructive) jaundice: gallstones, pancreatic carcinoma, cholangiocarcinoma, primary biliary cholangitis.",
"Dubin-Johnson syndrome and Rotor syndrome (rare congenital conjugated hyperbilirubinemia).",
],
causes_low=[
"Absent in pre-hepatic (haemolytic) jaundice — bilirubin produced is unconjugated and cannot be excreted in urine.",
"False negative: prolonged exposure to light degrades bilirubin in the specimen.",
],
clinical_manifestations=[
"Jaundice — yellow discolouration of skin, sclerae, and mucous membranes.",
"Dark (tea/cola-coloured) urine.",
"Pale (acholic) stools in obstructive jaundice.",
"Pruritus (bile salt deposition in skin).",
"Fatigue, anorexia, nausea, right upper quadrant pain.",
],
organs_affected=[
"Liver (hepatocytes, bile canaliculi).",
"Biliary system (gallbladder, bile ducts).",
"Kidneys (glomerular filtration of conjugated bilirubin).",
],
investigations=[
"Serum total, direct, and indirect bilirubin.",
"Liver function tests (ALT, AST, ALP, GGT, albumin, PT/INR).",
"Viral hepatitis serology (HBsAg, anti-HCV, anti-HAV IgM).",
"Abdominal ultrasound, CT, or MRCP to evaluate biliary obstruction.",
"Liver biopsy in uncertain cases.",
],
management=[
"Viral hepatitis: antiviral therapy (e.g., tenofovir for HBV; sofosbuvir-based regimens for HCV).",
"Obstructive jaundice: ERCP with stone removal or stenting; surgical bypass or Whipple's procedure for malignancy.",
"Alcoholic hepatitis: alcohol cessation, corticosteroids in severe cases (Maddrey score ≥ 32).",
"Drug-induced liver injury: withdrawal of offending drug.",
"Supportive: nutrition, vitamin K for coagulopathy.",
]
)
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 3: KETONES (KETONURIA)
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=3, name="Ketones (Ketonuria)",
normal_value="Negative. Trace amounts of ketones (acetoacetate, beta-hydroxybutyrate, acetone) are produced normally but not detectable by reagent strip.",
significance=[
"Ketones are produced in the liver by beta-oxidation of fatty acids when glucose availability is reduced or utilisation is impaired.",
"The three ketone bodies are acetoacetate, beta-hydroxybutyrate (most abundant), and acetone.",
"The reagent strip detects acetoacetate (and acetone) using the nitroprusside reaction; it does NOT detect beta-hydroxybutyrate directly.",
"Ketonuria indicates a shift from carbohydrate to fat metabolism — significant in diabetic ketoacidosis (DKA) and starvation.",
],
causes_high=[
"Diabetic ketoacidosis (DKA) — insulin deficiency causes uncontrolled lipolysis; most clinically urgent cause.",
"Starvation and prolonged fasting — carbohydrate depletion shifts metabolism to fat.",
"Low-carbohydrate / ketogenic diet.",
"Prolonged vomiting or diarrhoea with carbohydrate deprivation.",
"Alcoholic ketoacidosis — excessive alcohol, poor nutrition.",
"Febrile illness in children (especially with vomiting).",
"Post-anaesthesia, intense exercise, hyperthyroidism.",
],
causes_low=[
"Absence is normal.",
"Insulin therapy in DKA reduces ketogenesis.",
],
clinical_manifestations=[
"Nausea, vomiting, abdominal pain.",
"Fruity (acetone) breath.",
"Kussmaul respiration (deep, rapid breathing — compensatory for metabolic acidosis).",
"Dehydration, tachycardia, hypotension.",
"Altered consciousness, confusion, or coma in severe DKA.",
"In starvation: fatigue, weight loss, dizziness.",
],
organs_affected=[
"Liver (site of ketogenesis).",
"Kidneys (excretion of ketone bodies, electrolyte loss — potassium, sodium).",
"Brain and CNS (altered consciousness in severe ketoacidosis).",
"Cardiovascular system (arrhythmias due to hyperkalaemia/hypokalaemia).",
],
investigations=[
"Blood glucose — markedly elevated in DKA (typically > 14 mmol/L).",
"Arterial blood gas (ABG): metabolic acidosis (pH < 7.3, HCO3 < 15 mmol/L).",
"Serum electrolytes: Na, K, Cl, bicarbonate.",
"Serum beta-hydroxybutyrate (> 3 mmol/L confirms significant ketonaemia).",
"Anion gap calculation.",
"Full blood count, blood cultures if infection is the precipitant.",
],
management=[
"DKA: IV fluid resuscitation (0.9% NaCl), insulin infusion, potassium replacement (once K > 3.5 mmol/L), identify and treat precipitant.",
"Starvation ketonuria: oral or IV glucose supplementation, treat underlying cause.",
"Alcoholic ketoacidosis: IV dextrose and thiamine (before glucose), fluid replacement.",
"Monitoring: hourly blood glucose and ketones, 2-hourly electrolytes until resolution.",
]
)
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 4: BLOOD (HAEMATURIA / HAEMOGLOBINURIA)
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=4, name="Blood (Haematuria / Haemoglobinuria)",
normal_value="Negative. Up to 1–2 red blood cells per high-power field (HPF) on microscopy is considered normal; reagent strip is negative.",
significance=[
"The blood parameter on the reagent strip detects haemoglobin via its pseudoperoxidase activity (catalyses oxidation of a chromogen by hydrogen peroxide).",
"A positive result may indicate haematuria (intact RBCs), haemoglobinuria (free haemoglobin from intravascular haemolysis), or myoglobinuria (from rhabdomyolysis).",
"Microscopy is essential to differentiate these three causes (RBCs visible only in haematuria).",
"Even trace haematuria can be significant and requires follow-up investigation.",
],
causes_high=[
"Haematuria: urinary tract infection (UTI), renal calculi (kidney stones), glomerulonephritis, bladder cancer, renal cell carcinoma, trauma, benign prostatic hyperplasia (BPH), polycystic kidney disease, anticoagulant therapy.",
"Haemoglobinuria: intravascular haemolysis (haemolytic anaemia, transfusion reaction, PNH, G6PD deficiency, malaria).",
"Myoglobinuria: rhabdomyolysis (crush injury, statin myopathy, extreme exercise, heat stroke).",
"False positive: contamination with menstrual blood, oxidising agents (e.g., bleach residue in urine container).",
],
causes_low=[
"Absence is normal.",
"False negative: high levels of ascorbic acid (vitamin C) can inhibit the reaction.",
],
clinical_manifestations=[
"Macroscopic haematuria: visible red, pink, or brown urine.",
"Microscopic haematuria: no colour change; detected only on dipstick or microscopy.",
"Dysuria, frequency, urgency (UTI).",
"Flank pain radiating to groin (renal colic from stones).",
"Periorbital oedema, hypertension, oliguria (glomerulonephritis).",
"Myoglobinuria: dark (cola-coloured) urine, muscle pain, weakness, acute kidney injury.",
],
organs_affected=[
"Kidneys (glomerulonephritis, renal cell carcinoma, polycystic kidneys, stones).",
"Urinary bladder (bladder carcinoma, cystitis).",
"Urethra and prostate (BPH, urethritis).",
"Red blood cells / vascular system (haemolytic causes).",
"Skeletal muscle (myoglobinuria).",
],
investigations=[
"Urine microscopy: confirm RBCs; dysmorphic RBCs suggest glomerular origin.",
"Urine culture and sensitivity (if UTI suspected).",
"Renal function tests (urea, creatinine, eGFR).",
"CT urogram (gold standard for urological causes — stones, tumours).",
"Cystoscopy (for bladder pathology, especially in painless haematuria > 40 years).",
"Renal biopsy (for suspected glomerulonephritis).",
"Serum LDH, haptoglobin, blood film (haemolysis).",
"Creatine kinase (CK) for rhabdomyolysis.",
],
management=[
"UTI: antibiotics (trimethoprim, nitrofurantoin, cefalexin based on culture).",
"Renal calculi: hydration, analgesia (NSAIDs/opioids), lithotripsy or ureteroscopy for large stones.",
"Bladder/renal malignancy: oncological referral; TURBT, radical cystectomy, nephrectomy as appropriate.",
"Glomerulonephritis: immunosuppression (steroids, cyclophosphamide) depending on subtype.",
"Rhabdomyolysis: aggressive IV fluid resuscitation to prevent acute kidney injury.",
]
)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 5: pH
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=5, name="pH",
normal_value="4.5 – 8.0 (average ~6.0). Normal urine is slightly acidic. The kidney can produce urine ranging from pH 4.5 to 8.5 to maintain acid-base balance.",
significance=[
"Urine pH reflects the kidney's role in regulating systemic acid-base balance by excreting hydrogen ions or bicarbonate.",
"Urine is typically more acidic in the morning (concentrated overnight urine with more metabolic acids).",
"pH influences the solubility of urinary substances: acidic urine promotes uric acid and cystine crystal formation; alkaline urine promotes calcium phosphate and struvite crystal formation.",
"Reagent strip uses double indicator dye method (methyl red and bromothymol blue); measures pH in increments of 1.",
],
causes_high=[
"Alkaline urine (pH > 7.0): urinary tract infection with urease-producing organisms (Proteus, Klebsiella, Pseudomonas), renal tubular acidosis (RTA) Type I and II, metabolic alkalosis, vegetarian diet (high fruit/vegetable intake), vomiting (loss of HCl), administration of bicarbonate or acetazolamide, prolonged standing of specimen (bacterial breakdown of urea to ammonia).",
],
causes_low=[
"Acidic urine (pH < 6.0): high-protein diet, metabolic acidosis (DKA, lactic acidosis), respiratory acidosis, pyrexia, severe diarrhoea (bicarbonate loss), starvation/fasting, allopurinol therapy.",
],
clinical_manifestations=[
"Acidic urine: associated with uric acid stones (gout), cystine stones, metabolic/respiratory acidosis symptoms (Kussmaul breathing, confusion, lethargy).",
"Alkaline urine: associated with struvite (infection) stones, calcium phosphate stones; in RTA: muscle weakness, hypokalaemia, osteomalacia.",
"In UTI with urease-positive bacteria: offensive ammoniacal smell, recurrent stones.",
],
organs_affected=[
"Kidneys (tubular function — H+ excretion, HCO3 reabsorption).",
"Lungs (respiratory compensatory mechanisms).",
"Urinary tract (stone formation depends on pH).",
],
investigations=[
"Arterial blood gas (ABG) for systemic acid-base status.",
"Serum electrolytes (anion gap calculation).",
"Urine culture (for urease-positive UTI).",
"Urine pH in morning specimen (for RTA: inability to acidify urine below 5.5 in Type 1 RTA).",
"24-hour urine uric acid or calcium levels (stone workup).",
"Ammonium chloride loading test for incomplete RTA.",
],
management=[
"Acidosis management: treat underlying cause (insulin/fluids for DKA; bicarbonate in specific circumstances).",
"Alkalosis management: correct volume depletion, treat vomiting, potassium replacement.",
"Urinary alkalinisation: sodium bicarbonate or potassium citrate to prevent uric acid/cystine stones.",
"Urinary acidification: rarely needed; ammonium chloride used to prevent struvite stones.",
"Antibiotic therapy for urease-positive UTI to prevent struvite stone formation.",
]
)
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 6: PROTEIN (PROTEINURIA)
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=6, name="Protein (Proteinuria)",
normal_value="Negative (< 150 mg/day total urinary protein; < 30 mg/day albumin). Reagent strip is negative for protein in normal urine.",
significance=[
"The glomerular filtration membrane (podocytes, basement membrane, endothelial cells) prevents most proteins from entering the filtrate; small proteins that do pass are reabsorbed by the proximal tubule.",
"Persistent proteinuria is one of the most important indicators of renal disease and is associated with progressive loss of kidney function.",
"The reagent strip detects albumin preferentially (via protein-error-of-indicators method); it is less sensitive to globulins, Bence-Jones protein, and tubular proteins.",
"Microalbuminuria (30–300 mg/day) is the earliest marker of diabetic nephropathy and hypertensive nephropathy.",
],
causes_high=[
"Glomerular proteinuria: glomerulonephritis, diabetic nephropathy, hypertensive nephropathy, lupus nephritis, pre-eclampsia, nephrotic syndrome.",
"Tubular proteinuria: acute tubular necrosis (ATN), Fanconi syndrome, heavy metal toxicity, analgesic nephropathy.",
"Overflow proteinuria: multiple myeloma (Bence-Jones protein), haemolysis (haemoglobin), rhabdomyolysis (myoglobin).",
"Transient/benign proteinuria: fever, strenuous exercise, orthostatic (postural) proteinuria (common in young adults).",
"False positive: highly alkaline urine, contamination with antiseptics (chlorhexidine), prolonged dipstick immersion.",
],
causes_low=[
"Absence is normal.",
"False negative: dilute urine may give negative result despite significant proteinuria; Bence-Jones and tubular proteins may be missed by dipstick.",
],
clinical_manifestations=[
"Nephrotic syndrome: massive proteinuria (> 3.5 g/day), hypoalbuminaemia, generalised oedema (periorbital, peripheral, ascites), hyperlipidaemia, lipiduria.",
"Nephritic syndrome: haematuria, hypertension, oliguria, mild-moderate proteinuria.",
"Chronic kidney disease: fatigue, nocturia, hypertension, anaemia, uraemic symptoms.",
"Pre-eclampsia: hypertension + proteinuria ≥ 300 mg/day after 20 weeks of gestation, headache, visual disturbances.",
"Frothy or foamy urine (due to protein lowering surface tension).",
],
organs_affected=[
"Kidneys (glomeruli and tubules — primary site).",
"Cardiovascular system (hypertension, accelerated atherosclerosis from hyperlipidaemia in nephrotic syndrome).",
"Liver (increased lipoprotein synthesis in nephrotic syndrome).",
"Bones (calcium/phosphate imbalance in CKD).",
],
investigations=[
"Urine protein: creatinine ratio (spot urine): ≥ 30 mg/mmol significant; ≥ 300 mg/mmol = nephrotic range.",
"24-hour urine protein quantification (gold standard).",
"Urine albumin: creatinine ratio (ACR) for microalbuminuria screening.",
"Serum albumin, cholesterol, renal function (urea, creatinine, eGFR).",
"Complement levels (C3, C4), ANA, anti-dsDNA, ANCA (for autoimmune glomerulonephritis).",
"Serum protein electrophoresis and immunofixation (for myeloma).",
"Renal biopsy for definitive diagnosis of glomerulonephritis.",
],
management=[
"ACE inhibitors / ARBs: first-line to reduce proteinuria and slow CKD progression (independent of antihypertensive effect).",
"Blood pressure control: target < 130/80 mmHg in proteinuric CKD.",
"SGLT2 inhibitors (e.g., dapagliflozin): proven to reduce proteinuria and CKD progression.",
"Nephrotic syndrome: diuretics for oedema, statins for dyslipidaemia, anticoagulation if thrombosis risk high.",
"Immunosuppression: steroids (minimal change disease), cyclophosphamide/rituximab (FSGS, membranous nephropathy, lupus nephritis).",
"Pre-eclampsia: antihypertensives (labetalol, nifedipine), magnesium sulphate (eclampsia prevention), delivery of fetus is definitive treatment.",
]
)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 7: UROBILINOGEN
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=7, name="Urobilinogen",
normal_value="0.1 – 1.0 mg/dL (1.7 – 17 µmol/L). Small amounts are normally present in urine.",
significance=[
"Urobilinogen is produced in the intestine by bacterial reduction of conjugated bilirubin (urobilin).",
"Most urobilinogen is reabsorbed into the portal circulation, processed by the liver (enterohepatic circulation), and a small fraction is excreted in urine.",
"Measuring urine urobilinogen helps differentiate types of jaundice: elevated in haemolytic and hepatocellular jaundice; absent in obstructive (cholestatic) jaundice.",
"Reagent strip uses Ehrlich's aldehyde reaction or modified diazonium salt reaction.",
],
causes_high=[
"Haemolytic anaemia — increased bilirubin production overwhelms hepatic processing; more urobilinogen formed in gut.",
"Hepatocellular disease (hepatitis, cirrhosis) — impaired re-uptake of urobilinogen from portal blood.",
"Portosystemic shunts — urobilinogen bypasses hepatic clearance.",
"Constipation — prolonged intestinal transit increases bacterial conversion and absorption.",
"False positive: porphobilinogen (present in porphyria) gives positive Ehrlich reaction.",
],
causes_low=[
"Obstructive (cholestatic) jaundice — bile flow to intestine blocked; no bilirubin reaches gut, therefore no urobilinogen formed; urine urobilinogen is absent.",
"Antibiotic therapy — reduces intestinal bacteria that produce urobilinogen.",
"False negative: prolonged exposure to light destroys urobilinogen in specimen.",
],
clinical_manifestations=[
"Elevated urobilinogen (haemolytic): anaemia symptoms (pallor, fatigue, breathlessness, tachycardia), jaundice, splenomegaly, dark urine.",
"Elevated urobilinogen (hepatocellular): fatigue, anorexia, nausea, jaundice, hepatomegaly.",
"Absent urobilinogen (obstructive): dark urine (bilirubinuria), pale stools, itching, jaundice.",
],
organs_affected=[
"Liver (conjugation and re-uptake of bilirubin/urobilinogen).",
"Gastrointestinal tract (site of urobilinogen formation by gut bacteria).",
"Red blood cells (haemolytic causes).",
"Kidneys (excretion of excess urobilinogen).",
],
investigations=[
"Serum total, direct, and indirect bilirubin.",
"Full blood count, blood film, reticulocyte count (for haemolysis).",
"LDH, haptoglobin, direct antiglobulin test (DAT) for haemolytic anaemia.",
"Liver function tests and hepatitis serology.",
"Abdominal ultrasound or MRCP for biliary obstruction.",
"Urine bilirubin (negative in haemolytic jaundice, positive in obstructive/hepatocellular).",
],
management=[
"Haemolytic anaemia: treat underlying cause (immunosuppression for autoimmune, exchange transfusion for severe cases, folic acid supplementation).",
"Hepatocellular disease: antiviral therapy, alcohol cessation, supportive care.",
"Biliary obstruction: ERCP, stenting, or surgical intervention.",
]
)
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 8: NITRITE
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=8, name="Nitrite",
normal_value="Negative. Nitrite is not normally present in urine.",
significance=[
"Nitrite is not a normal urinary constituent. Its presence indicates a urinary tract infection (UTI) with nitrite-reducing bacteria.",
"Dietary nitrates are excreted in urine. Gram-negative bacteria (e.g., Escherichia coli, Klebsiella, Proteus) contain nitrate reductase enzymes that convert nitrate to nitrite.",
"The reagent strip uses the Greiss reaction: nitrite reacts with an aromatic amine (sulphanilic acid) to form a diazonium compound, which then couples with another reagent to produce a pink colour.",
"Positive nitrite has high specificity (~92–99%) but relatively low sensitivity (~40–70%) for UTI — a negative result does not exclude infection.",
],
causes_high=[
"Gram-negative UTI: E. coli (most common), Klebsiella pneumoniae, Proteus mirabilis, Enterobacter, Pseudomonas.",
"Note: Gram-positive organisms (Staphylococcus saprophyticus, Enterococcus) and Candida do NOT produce nitrite — false negative in these infections.",
"False positive: prolonged urine storage, contamination, specimen left at room temperature (bacterial overgrowth).",
],
causes_low=[
"Negative in UTIs caused by non-nitrite-reducing organisms.",
"Dilute urine or inadequate bladder dwell time (< 4 hours) reduces sensitivity.",
"High ascorbic acid intake can inhibit the Greiss reaction (false negative).",
],
clinical_manifestations=[
"Lower UTI (cystitis): dysuria (burning on urination), urinary frequency and urgency, suprapubic pain, haematuria, cloudy and malodorous urine.",
"Upper UTI (pyelonephritis): high fever, rigors, flank pain (costovertebral angle tenderness), nausea, vomiting, systemic illness.",
"Asymptomatic bacteriuria: no symptoms; detected incidentally on routine urinalysis (treatment indicated in pregnant women).",
"In children: fever, irritability, vomiting, poor feeding, bedwetting.",
],
organs_affected=[
"Urinary bladder (cystitis — most common site).",
"Kidneys and renal pelvis (pyelonephritis).",
"Urethra (urethritis).",
"Prostate (prostatitis in males).",
],
investigations=[
"Urine microscopy: pyuria (> 10 WBC/HPF), bacteriuria, possible RBCs.",
"Urine culture and sensitivity (MSU or catheter specimen) — gold standard for UTI diagnosis; identifies organism and antibiotic sensitivities.",
"Blood cultures if pyelonephritis or urosepsis suspected.",
"Renal ultrasound (for structural abnormalities, hydronephrosis, abscess).",
"Cystoscopy if recurrent UTIs or haematuria.",
],
management=[
"Uncomplicated lower UTI in women: trimethoprim 200 mg BD × 7 days; nitrofurantoin 100 mg MR BD × 5 days; or cefalexin.",
"Pyelonephritis (outpatient): ciprofloxacin 500 mg BD × 7–14 days or co-amoxiclav (guided by culture).",
"Severe pyelonephritis / urosepsis: IV ceftriaxone or piperacillin-tazobactam; escalate if resistant organisms.",
"Recurrent UTIs: low-dose prophylactic antibiotics, post-coital antibiotics, cranberry products (some evidence for prevention).",
"Asymptomatic bacteriuria in pregnancy: treat to prevent pyelonephritis and preterm labour.",
]
)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 9: LEUKOCYTE ESTERASE
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=9, name="Leukocyte Esterase",
normal_value="Negative. Leukocyte esterase is not normally detectable in urine; < 5 WBCs/HPF on microscopy is normal.",
significance=[
"Leukocyte esterase is an enzyme released from lysed neutrophils (polymorphonuclear leukocytes, PMNs). Its presence indicates pyuria (white blood cells in urine).",
"The reagent strip uses an indoxyl ester substrate that, in the presence of leukocyte esterase, is hydrolysed to indoxyl, which then reacts with a diazonium salt to produce a purple colour.",
"Pyuria is a strong indicator of urinary tract infection (UTI) but can occur in sterile conditions (sterile pyuria).",
"Combined with nitrite positivity, it has a high predictive value (sensitivity ~75–90%) for bacterial UTI.",
],
causes_high=[
"Urinary tract infection (UTI) — most common cause; cystitis, pyelonephritis, urethritis, prostatitis.",
"Sterile pyuria: TB of the urinary tract (acid-fast bacilli not detected by standard culture), interstitial nephritis (drug-induced — NSAIDs, antibiotics), renal calculi causing urothelial irritation, SLE nephritis, chlamydial or gonococcal urethritis (sexually transmitted infections), vaginal contamination in females.",
"False positive: vaginal contamination, samples contaminated with oxidising cleaning agents, Trichomonas vaginalis.",
"False negative: high glucose or protein concentrations, high specific gravity, high ascorbic acid, prolonged specimen transport.",
],
causes_low=[
"Absence of significant inflammation; normal finding.",
"False negative as described above.",
],
clinical_manifestations=[
"Symptoms of UTI: dysuria, frequency, urgency, suprapubic discomfort.",
"Sterile pyuria: may be asymptomatic or associated with constitutional symptoms (weight loss, night sweats, haematuria suggesting TB).",
"Interstitial nephritis: fever, rash, eosinophilia (drug-induced), declining renal function.",
"Pyuria in urolithiasis: haematuria, renal colic.",
],
organs_affected=[
"Urinary bladder (cystitis, stones, carcinoma).",
"Kidneys (pyelonephritis, interstitial nephritis, renal TB).",
"Urethra and prostate (urethritis, prostatitis).",
"Genitalia (STI-related: Chlamydia, Gonorrhoea).",
],
investigations=[
"Urine culture and sensitivity (MSU) — essential to identify causative organism and guide antibiotic treatment.",
"Urine for acid-fast bacilli (AFB) and mycobacterial culture × 3 early morning specimens (if TB suspected).",
"Urine cytology (if malignancy suspected as cause of sterile pyuria).",
"Cystoscopy and biopsy (interstitial cystitis, bladder carcinoma).",
"Renal biopsy (interstitial nephritis).",
"STI swabs (cervical, urethral) for Chlamydia and Gonorrhoea.",
],
management=[
"UTI: antibiotics as per culture and sensitivity (see Nitrite section).",
"Sterile pyuria — renal TB: standard TB regimen (HRZE × 2 months, then HR × 4 months).",
"Drug-induced interstitial nephritis: discontinue offending drug; corticosteroids may accelerate recovery.",
"STIs: azithromycin or doxycycline (Chlamydia); ceftriaxone + azithromycin (Gonorrhoea).",
"Interstitial cystitis: low-acid diet, bladder training, amitriptyline, intravesical treatments.",
]
)
# ════════════════════════════════════════════════════════════════════════════════
# PARAMETER 10: SPECIFIC GRAVITY
# ════════════════════════════════════════════════════════════════════════════════
add_parameter(
number=10, name="Specific Gravity",
normal_value="1.003 – 1.035 (normal random specimen: 1.016 – 1.022 over 24 hours). Specific gravity of distilled water = 1.000.",
significance=[
"Specific gravity measures the density of urine relative to distilled water; it reflects the concentration of all dissolved solutes (urea 20%, NaCl 25%, sulphate, phosphate, and other metabolites).",
"It provides an assessment of the kidney's ability to concentrate or dilute urine in response to fluid balance and ADH (antidiuretic hormone) secretion.",
"A specific gravity ≥ 1.023 in a random specimen indicates adequate concentrating ability.",
"Isosthenuria (fixed SG ~1.010) indicates loss of both concentrating and diluting ability — a marker of severe renal damage.",
"Reagent strip method: uses change in pKa of polyelectrolytes with ionic concentration; provides indirect estimation in increments of 0.005.",
],
causes_high=[
"Dehydration and volume depletion (most common — SG > 1.030).",
"Syndrome of inappropriate ADH secretion (SIADH).",
"Glycosuria — glucose increases solute content (SG elevated disproportionately to osmolality).",
"Proteinuria (massive) — protein is a large molecule that raises SG.",
"Heart failure, liver cirrhosis with ascites (reduced renal perfusion).",
"Adrenal insufficiency (Addison's disease).",
"Radiographic contrast media excretion.",
],
causes_low=[
"Overhydration, excessive fluid intake (SG < 1.005).",
"Diabetes insipidus (central or nephrogenic) — ADH absent or ineffective; SG as low as 1.001–1.003, large volumes of dilute urine.",
"Chronic renal failure — loss of concentrating ability.",
"Pyelonephritis (chronic), glomerulonephritis.",
"Hypokalemia and hypercalcaemia (impair tubular concentration).",
"Diuretic use.",
],
clinical_manifestations=[
"High SG (concentrated urine): dark-coloured urine, decreased urine output, thirst, dry mucous membranes — features of dehydration.",
"In SIADH: hyponatraemia causing headache, confusion, seizures, coma.",
"Low SG (dilute urine): polyuria, polydipsia.",
"Diabetes insipidus: large volumes (> 3–20 L/day) of colourless urine, severe thirst, hypernatraemia (if fluid intake inadequate).",
"Isosthenuria: features of CKD — fatigue, anaemia, uraemic symptoms, oedema.",
],
organs_affected=[
"Kidneys (renal tubular concentrating/diluting mechanism — loop of Henle, collecting duct).",
"Hypothalamus and posterior pituitary (ADH synthesis and secretion — central DI).",
"Cardiovascular system (heart failure causing pre-renal reduced perfusion).",
"Liver (cirrhosis with splanchnic vasodilation and renal hypoperfusion).",
],
investigations=[
"Urine osmolality (more precise than SG; > 800 mOsm/kg = adequate concentration).",
"Paired serum and urine osmolality.",
"Water deprivation test (with desmopressin challenge) to differentiate central DI from nephrogenic DI and psychogenic polydipsia.",
"Serum sodium and electrolytes.",
"Serum ADH/copeptin levels.",
"Renal function tests (urea, creatinine, eGFR) for CKD.",
"BNP/NT-proBNP, echocardiography (heart failure).",
"Liver function tests, liver ultrasound (cirrhosis).",
],
management=[
"Dehydration: oral or IV fluid rehydration; treat underlying cause.",
"Central diabetes insipidus: intranasal or oral desmopressin (DDAVP).",
"Nephrogenic diabetes insipidus: low-sodium/low-protein diet, thiazide diuretics, NSAIDs (paradoxically reduce urine output), treat underlying cause (stop offending drug, correct hypercalcaemia/hypokalaemia).",
"SIADH: fluid restriction (< 1 L/day), hypertonic saline in severe symptomatic hyponatraemia, tolvaptan (vasopressin V2 receptor antagonist).",
"Heart failure / cirrhosis: treat underlying condition; diuretics.",
"CKD with isosthenuria: manage as CKD (ACE inhibitors, blood pressure control, dietary protein restriction, renal replacement therapy when ESRD).",
]
)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# CONCLUSION
# ════════════════════════════════════════════════════════════════════════════════
add_heading("Conclusion", level=1)
add_para(
"The chemical examination of urine through the reagent dipstick method provides a rapid, cost-effective, "
"and invaluable screening tool in clinical practice. The ten parameters reviewed in this report — glucose, "
"bilirubin, ketones, blood, pH, protein, urobilinogen, nitrite, leukocyte esterase, and specific gravity — "
"each reflect specific physiological and pathological processes occurring in the kidneys, urinary tract, and "
"systemic organ systems."
)
add_para(
"Glucosuria is the hallmark of uncontrolled diabetes mellitus; bilirubinuria indicates hepatobiliary disease; "
"ketonuria signals fat catabolism or diabetic ketoacidosis; haematuria warrants investigation for urological "
"malignancy, renal disease, or infection. Urine pH guides acid-base interpretation and stone risk; proteinuria "
"remains the most sensitive early marker of glomerular injury; urobilinogen differentiates types of jaundice. "
"Nitrite and leukocyte esterase together provide strong evidence for urinary tract infection, while specific "
"gravity reflects the kidney's concentrating ability and overall hydration status."
)
add_para(
"No single parameter should be interpreted in isolation. The combination of urinalysis findings with clinical "
"context, further laboratory investigations, and imaging studies is essential for accurate diagnosis and "
"patient management. Health science students must be proficient in interpreting urinalysis results, "
"recognising both true positives and the limitations of the dipstick method (false positives/negatives), "
"and selecting appropriate confirmatory investigations to guide treatment decisions."
)
page_break()
# ════════════════════════════════════════════════════════════════════════════════
# REFERENCES
# ════════════════════════════════════════════════════════════════════════════════
add_heading("References", level=1)
refs = [
"Henry, J. B. (Ed.). (2021). Henry's Clinical Diagnosis and Management by Laboratory Methods (24th ed.). Elsevier.",
"McPherson, R. A., & Pincus, M. R. (2022). Henry's Clinical Diagnosis and Management by Laboratory Methods. Elsevier Saunders.",
"Kasper, D. L., Fauci, A. S., Hauser, S. L., Longo, D. L., Jameson, J. L., & Loscalzo, J. (2022). Harrison's Principles of Internal Medicine (22nd ed.). McGraw-Hill.",
"Goldman, L., & Schafer, A. I. (2020). Goldman-Cecil Medicine (26th ed.). Elsevier.",
"Kumar, V., Abbas, A. K., & Aster, J. C. (2021). Robbins and Cotran Pathologic Basis of Disease (10th ed.). Elsevier Saunders.",
"Braunwald, E., Zipes, D. P., & Libby, P. (2021). Braunwald's Heart Disease: A Textbook of Cardiovascular Medicine (11th ed.). Elsevier.",
"Morgan, G. E., Mikhail, M. S., & Murray, M. J. (2022). Clinical Anesthesiology (7th ed.). McGraw-Hill.",
"American Diabetes Association. (2024). Standards of Medical Care in Diabetes — 2024. Diabetes Care, 47(Suppl. 1), S1–S321.",
"National Institute for Health and Care Excellence (NICE). (2023). Urinary tract infection (lower): Antimicrobial prescribing. NICE Guideline NG109.",
"World Health Organization. (2019). WHO Guidelines on the Management of Urinary Tract Infections.",
"Lamb, E. J., & Price, C. P. (2019). Kidney function tests. In W. J. Marshall, S. K. Bangert, & M. Lapsley (Eds.), Clinical Biochemistry: Metabolic and Clinical Aspects (3rd ed., pp. 258–282). Churchill Livingstone.",
"Simerville, J. A., Maxted, W. C., & Pahira, J. J. (2005). Urinalysis: A comprehensive review. American Family Physician, 71(6), 1153–1162.",
]
for i, ref in enumerate(refs, 1):
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
set_line_spacing_15(p)
# Hanging indent
p.paragraph_format.left_indent = Inches(0.5)
p.paragraph_format.first_line_indent = Inches(-0.5)
r = p.add_run(f"{i}. {ref}")
r.font.name = 'Times New Roman'
r.font.size = Pt(12)
# ─── SAVE ────────────────────────────────────────────────────────────────────
output_path = "/tmp/workspace/urinalysis-report/Urinalysis_Lab_Assignment_Report.docx"
doc.save(output_path)
print(f"Saved: {output_path}")