I need complete study material for Diabetes mellitus 1. Include biochemistry of insulin formation and glucose metabolism 2. Pharmacological drugs with classifications and receptors where they function. 3. Retinopathy associations 4. Nephropathy associations 5. Infant of diabetic mother 6. Types of insulin supplements given. 7. Diabetic foot 8. Cardiac associations 9. Non alcoholic fatty liver disease 10. Diagnosis of DM, tests markers and values . Arrange the shared list in the correct order of study and make a downloadable pdf.
Generate a complete PDF study guide covering all 10 diabetes topics in the correct order
I'll work through all 10 topics in order and compile one final PDF. Which topic should I research and write first?
You are researching medical textbook content for a study guide on Diabetes Mellitus. Use the medical-library skill workflow: query_library_db (SQLite, read-only, max 20 rows/query) against the textbook database, and read_file to pull full paragraph text from block file paths returned by the DB queries. You have a STRICT LIMIT of 5 total query_library_db calls for this entire task, so batch your searches efficiently (combine multiple keyword searches thoughtfully, prioritize headings_fts and paragraphs_fts FTS5 searches, and use read_file sparingly only for key sections). You do NOT have access to fetch_image or search_image in this task - skip images entirely, text only. Research and write detailed, well-organized study notes (with clear headings, subheadings, bullet points, and tables where useful) for these 5 topics on Diabetes Mellitus, in this order: 1. Biochemistry of insulin formation and glucose metabolism - insulin gene expression, preproinsulin -> proinsulin -> insulin + C-peptide processing, beta cell secretion mechanism (glucose sensing via GLUT2/glucokinase, ATP-sensitive K+ channel closure, calcium influx, exocytosis), insulin receptor structure and signaling (tyrosine kinase, IRS, PI3K/Akt, GLUT4 translocation), glucose metabolism pathways affected by insulin (glycolysis, gluconeogenesis, glycogenesis/glycogenolysis, lipogenesis), counter-regulatory hormones (glucagon, cortisol, epinephrine, growth hormone). 2. Diagnosis of Diabetes Mellitus - diagnostic criteria and tests: Fasting Plasma Glucose (FPG), Oral Glucose Tolerance Test (OGTT), HbA1c, random plasma glucose with symptoms, exact cutoff values (mg/dL and mmol/L) for normal/prediabetes/diabetes, gestational diabetes screening criteria, autoantibody markers for Type 1 DM (GAD65, IA-2, ICA, insulin autoantibodies), C-peptide levels, urine markers (glucosuria, ketonuria, microalbuminuria), and classification of DM types (Type 1, Type 2, gestational, MODY, secondary causes). 3. Pharmacological drugs for Diabetes Mellitus - full classification list with mechanism and receptor/target for each class: Biguanides (metformin - AMPK activation), Sulfonylureas (glibenclamide, glipizide - SUR1/Kir6.2 ATP-sensitive K+ channel), Meglitinides, Thiazolidinediones (pioglitazone - PPAR-gamma), Alpha-glucosidase inhibitors (acarbose), DPP-4 inhibitors (sitagliptin - dipeptidyl peptidase-4), GLP-1 receptor agonists (exenatide, liraglutide, semaglutide - GLP-1 receptor), SGLT2 inhibitors (empagliflozin, dapagliflozin - sodium-glucose cotransporter 2), Amylin analogs (pramlintide), and any others found. Include mechanism of action, receptor/target, and key side effects for each class. 4. Types of insulin supplements/preparations - Rapid-acting (lispro, aspart, glulisine), Short-acting/Regular insulin, Intermediate-acting (NPH), Long-acting (glargine, detemir, degludec), Premixed insulin formulations. Include onset, peak, duration of action for each, and clinical use notes. 5. Diabetic Retinopathy - pathophysiology (microvascular damage, pericyte loss, basement membrane thickening), classification (non-proliferative vs proliferative diabetic retinopathy), clinical features/fundoscopic findings (microaneurysms, dot-blot hemorrhages, cotton wool spots, neovascularization, macular edema), diagnosis, and management/treatment (laser photocoagulation, anti-VEGF therapy). For EVERY fact pulled from the textbook database, cite it as: - Book Title, p. XXX (use whatever page/section identifier is available from the DB, e.g. section heading or block info; if no page number, cite as - Book Title, [section heading]). Return your FULL final answer as complete, well-formatted markdown study notes covering all 5 topics above, organized with clear headings (## for each topic, ### for subsections), bullet points, and tables where appropriate. This will be inserted directly into a study guide PDF, so make it thorough, accurate, and well-structured. Do not include meta-commentary about your research process - just the final study content with citations.
You are researching medical textbook content for a study guide on Diabetes Mellitus. Use the medical-library skill workflow: query_library_db (SQLite, read-only, max 20 rows/query) against the textbook database, and read_file to pull full paragraph text from block file paths returned by the DB queries. You have a STRICT LIMIT of 5 total query_library_db calls for this entire task, so batch your searches efficiently (combine multiple keyword searches thoughtfully, prioritize headings_fts and paragraphs_fts FTS5 searches, and use read_file sparingly only for key sections). You do NOT have access to fetch_image or search_image in this task - skip images entirely, text only. Research and write detailed, well-organized study notes (with clear headings, subheadings, bullet points, and tables where useful) for these 5 topics on Diabetes Mellitus, in this order: 1. Diabetic Nephropathy - pathophysiology (glomerular hyperfiltration, mesangial expansion, Kimmelstiel-Wilson nodules, glomerular basement membrane thickening), stages of diabetic kidney disease, clinical markers (microalbuminuria, macroalbuminuria, GFR decline, proteinuria), diagnosis and screening recommendations, and management (ACE inhibitors/ARBs, SGLT2 inhibitors renal protection, glycemic control targets). 2. Diabetic Foot - pathophysiology (peripheral neuropathy - sensory/motor/autonomic, peripheral arterial disease, immunopathy/infection susceptibility), clinical features (ulceration patterns, Charcot foot, callus formation, loss of protective sensation), classification systems (Wagner classification or University of Texas classification), diagnosis (monofilament testing, ankle-brachial index, vibration perception), and management/prevention (foot care, debridement, offloading, antibiotics, revascularization). 3. Cardiac associations of Diabetes Mellitus - mechanisms of accelerated atherosclerosis, diabetic cardiomyopathy (mechanisms independent of coronary disease), coronary artery disease risk and silent myocardial ischemia in diabetics, autonomic neuropathy affecting the heart, heart failure risk, and management considerations (statins, blood pressure control, specific cardioprotective diabetes drugs like SGLT2 inhibitors and GLP-1 agonists). 4. Non-Alcoholic Fatty Liver Disease (NAFLD) in the context of Diabetes Mellitus - pathophysiology and link to insulin resistance, lipotoxicity, spectrum of disease (simple steatosis to NASH to cirrhosis), diagnosis (liver enzymes, imaging, fibrosis scores, biopsy), and management (weight loss, glycemic control, pioglitazone, GLP-1 agonists effects on liver). 5. Infant of a Diabetic Mother (IDM) - pathophysiology (maternal hyperglycemia causing fetal hyperinsulinemia - Pedersen hypothesis), complications: macrosomia, neonatal hypoglycemia, respiratory distress syndrome, congenital malformations (caudal regression syndrome, cardiac defects), polycythemia, hyperbilirubinemia, hypocalcemia, hypomagnesemia. Include diagnosis/monitoring and management of the neonate. For EVERY fact pulled from the textbook database, cite it as: - Book Title, p. XXX (use whatever page/section identifier is available from the DB, e.g. section heading or block info; if no page number, cite as - Book Title, [section heading]). Return your FULL final answer as complete, well-formatted markdown study notes covering all 5 topics above, organized with clear headings (## for each topic, ### for subsections), bullet points, and tables where appropriate. This will be inserted directly into a study guide PDF, so make it thorough, accurate, and well-structured. Do not include meta-commentary about your research process - just the final study content with citations.
Which topic should I research in full depth first?
Which topic should I research in full depth first for your study notes?
Quick answer
| Pathway | Effect of Insulin |
|---|---|
| Glycolysis | Stimulates (via hexokinase, PFK-1, pyruvate kinase induction) |
| Glycogenesis | Stimulates (activates glycogen synthase) |
| Glycogenolysis | Inhibits |
| Gluconeogenesis | Inhibits (suppresses PEPCK, fructose-1,6-bisphosphatase, glucose-6-phosphatase) |
| Lipogenesis | Stimulates (activates acetyl-CoA carboxylase, fatty acid synthase) |
| Lipolysis | Inhibits (inhibits hormone-sensitive lipase) |
| Proteolysis | Inhibits; promotes protein synthesis |
| Test | Normal | Prediabetes | Diabetes |
|---|---|---|---|
| Fasting Plasma Glucose (FPG) | <100 mg/dL (5.6 mmol/L) | 100-125 mg/dL | ≥126 mg/dL (7.0 mmol/L) |
| 2-hr OGTT (75g glucose load) | <140 mg/dL | 140-199 mg/dL | ≥200 mg/dL (11.1 mmol/L) |
| HbA1c | <5.7% | 5.7-6.4% | ≥6.5% |
| Random Plasma Glucose + symptoms | - | - | ≥200 mg/dL |
| Class | Examples | Mechanism/Receptor Target | Key Side Effects |
|---|---|---|---|
| Biguanides | Metformin | Activates AMPK; decreases hepatic gluconeogenesis, increases peripheral insulin sensitivity | GI upset, lactic acidosis (rare), B12 deficiency |
| Sulfonylureas | Glibenclamide, Glipizide, Glimepiride | Bind SUR1 subunit of KATP channel on beta cells → closes channel → insulin release | Hypoglycemia, weight gain |
| Meglitinides | Repaglinide, Nateglinide | Same KATP/SUR1 site, faster/shorter action | Hypoglycemia (less than SU) |
| Thiazolidinediones (TZDs) | Pioglitazone, Rosiglitazone | Activate PPAR-gamma nuclear receptor → improves insulin sensitivity in adipose/muscle | Weight gain, fluid retention, heart failure risk, fracture risk |
| Alpha-glucosidase inhibitors | Acarbose, Miglitol | Inhibit intestinal alpha-glucosidase → delay carbohydrate absorption | Flatulence, GI upset |
| DPP-4 inhibitors (gliptins) | Sitagliptin, Vildagliptin, Linagliptin | Inhibit dipeptidyl peptidase-4 → increases endogenous GLP-1/GIP levels | Generally well tolerated; pancreatitis risk (rare) |
| GLP-1 receptor agonists | Exenatide, Liraglutide, Semaglutide, Dulaglutide | Agonists at GLP-1 receptor → glucose-dependent insulin secretion, decreases glucagon, delays gastric emptying, satiety | Nausea, vomiting, pancreatitis risk |
| SGLT2 inhibitors | Empagliflozin, Dapagliflozin, Canagliflozin | Inhibit sodium-glucose cotransporter 2 in proximal renal tubule → glucosuria | UTI, genital mycotic infections, euglycemic DKA |
| Amylin analogs | Pramlintide | Mimics amylin, co-secreted with insulin - slows gastric emptying, suppresses glucagon | Nausea, hypoglycemia (with insulin) |
| Insulin | (see section 4) | Insulin receptor (tyrosine kinase) | Hypoglycemia, weight gain |
| Type | Examples | Onset | Peak | Duration |
|---|---|---|---|---|
| Rapid-acting | Lispro, Aspart, Glulisine | 10-15 min | 1-2 hr | 3-5 hr |
| Short-acting (Regular) | Regular human insulin | 30-60 min | 2-3 hr | 5-8 hr |
| Intermediate-acting | NPH (isophane) | 2-4 hr | 4-10 hr | 10-16 hr |
| Long-acting | Glargine, Detemir | 1-2 hr | minimal peak | 20-24 hr |
| Ultra-long-acting | Degludec | 30-90 min | minimal peak | up to 42 hr |
| Premixed | 70/30 NPH/Regular, 75/25 lispro protamine/lispro | Combination profile | Combination | Combination |
Generate a downloadable PDF of this complete study guide
mkdir -p /tmp/workspace/diabetes-study-guide && ls -la /tmp/workspace/
~/diabetes-study-guide/build_pdf.py
#!/usr/bin/env python3
"""Build the Diabetes Mellitus Study Guide PDF."""
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
PageBreak, ListFlowable, ListItem, HRFlowable
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT
OUT = "/tmp/workspace/diabetes-study-guide/Diabetes_Mellitus_Study_Guide.pdf"
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="TitleBig", fontSize=24, leading=28, alignment=TA_CENTER,
textColor=colors.HexColor("#1a3d5c"), spaceAfter=6, fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Subtitle", fontSize=13, leading=16, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), spaceAfter=20, fontName="Helvetica"))
styles.add(ParagraphStyle(name="SectionHeading", fontSize=16, leading=20, spaceBefore=14, spaceAfter=8,
textColor=colors.white, backColor=colors.HexColor("#1a3d5c"),
fontName="Helvetica-Bold", leftIndent=6, borderPadding=6))
styles.add(ParagraphStyle(name="SubHeading", fontSize=12.5, leading=15, spaceBefore=10, spaceAfter=4,
textColor=colors.HexColor("#1a3d5c"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Body", fontSize=10, leading=14, spaceAfter=4, alignment=TA_LEFT, fontName="Helvetica"))
styles.add(ParagraphStyle(name="BulletBody", fontSize=10, leading=13.5, spaceAfter=2, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TOCItem", fontSize=11, leading=18, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableCell", fontSize=8.7, leading=11, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableHeader", fontSize=9, leading=11, fontName="Helvetica-Bold", textColor=colors.white))
def P(text):
return Paragraph(text, styles["Body"])
def bullets(items):
return ListFlowable(
[ListItem(Paragraph(i, styles["BulletBody"]), leftIndent=6) for i in items],
bulletType="bullet", start="•", leftIndent=14, spaceBefore=2, spaceAfter=6
)
def make_table(header, rows, col_widths=None):
data = [[Paragraph(h, styles["TableHeader"]) for h in header]]
for r in rows:
data.append([Paragraph(str(c), styles["TableCell"]) for c in r])
t = Table(data, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1a3d5c")),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#B0B0B0")),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#EEF3F7")]),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]))
return t
def section(num, title):
return Paragraph(f"{num}. {title}", styles["SectionHeading"])
def sub(title):
return Paragraph(title, styles["SubHeading"])
story = []
# ---------- Cover ----------
story.append(Spacer(1, 4 * cm))
story.append(Paragraph("Diabetes Mellitus", styles["TitleBig"]))
story.append(Paragraph("Complete Study Guide", styles["TitleBig"]))
story.append(Paragraph("Biochemistry · Diagnosis · Pharmacology · Complications · Special Populations", styles["Subtitle"]))
story.append(Spacer(1, 1*cm))
story.append(HRFlowable(width="80%", thickness=1, color=colors.HexColor("#1a3d5c"), hAlign="CENTER"))
story.append(Spacer(1, 1*cm))
toc_items = [
"1. Biochemistry of Insulin Formation and Glucose Metabolism",
"2. Diagnosis of Diabetes Mellitus — Tests, Markers, Values",
"3. Pharmacological Drugs — Classification and Receptors",
"4. Types of Insulin Supplements",
"5. Diabetic Retinopathy",
"6. Diabetic Nephropathy",
"7. Diabetic Foot",
"8. Cardiac Associations of Diabetes Mellitus",
"9. Non-Alcoholic Fatty Liver Disease (NAFLD)",
"10. Infant of a Diabetic Mother (IDM)",
]
story.append(Paragraph("Contents (Correct Study Order)", styles["SubHeading"]))
for item in toc_items:
story.append(Paragraph(item, styles["TOCItem"]))
story.append(PageBreak())
# ---------- 1. Biochemistry ----------
story.append(section(1, "Biochemistry of Insulin Formation and Glucose Metabolism"))
story.append(sub("Insulin Synthesis"))
story.append(bullets([
"Insulin gene (chromosome 11) transcribed in pancreatic beta cells → mRNA translated into <b>preproinsulin</b> on rough ER ribosomes.",
"Signal peptide cleaved → <b>proinsulin</b> (single chain: A-chain, B-chain, connecting C-peptide, held by 2 disulfide bonds).",
"Proinsulin transported to Golgi, packaged into secretory granules, cleaved by prohormone convertases (PC1/3, PC2) and carboxypeptidase E → <b>insulin (A+B chains linked by disulfide bonds) + C-peptide</b> in equimolar amounts.",
"C-peptide has no known metabolic activity but is a useful clinical marker of endogenous insulin production (unaffected by exogenous insulin injections).",
]))
story.append(sub("Insulin Secretion Mechanism (Beta Cell)"))
story.append(bullets([
"Glucose enters the beta cell via the <b>GLUT2</b> transporter.",
"Glucokinase phosphorylates glucose (rate-limiting "glucose sensor" step).",
"Glycolysis/oxidative metabolism raises the ATP:ADP ratio.",
"ATP closes <b>ATP-sensitive K+ channels (K<sub>ATP</sub>: SUR1/Kir6.2 subunits)</b> → membrane depolarization.",
"Voltage-gated Ca2+ channels open → Ca2+ influx → triggers exocytosis of insulin granules.",
"Biphasic release: first phase (stored granules, rapid) and second phase (newly synthesized insulin, sustained).",
]))
story.append(sub("Insulin Receptor and Signaling"))
story.append(bullets([
"Insulin receptor: tetrameric transmembrane <b>receptor tyrosine kinase</b> (2 alpha + 2 beta subunits).",
"Insulin binding → autophosphorylation of beta subunits → phosphorylates <b>IRS-1/IRS-2</b> → activates <b>PI3K/Akt pathway</b> → triggers <b>GLUT4 translocation</b> to the cell membrane in muscle/adipose tissue → glucose uptake.",
"A parallel <b>Ras/MAPK pathway</b> mediates insulin's growth/mitogenic effects.",
]))
story.append(sub("Glucose Metabolism — Insulin's Actions"))
story.append(make_table(
["Pathway", "Effect of Insulin"],
[
["Glycolysis", "Stimulates (hexokinase, PFK-1, pyruvate kinase induction)"],
["Glycogenesis", "Stimulates (activates glycogen synthase)"],
["Glycogenolysis", "Inhibits"],
["Gluconeogenesis", "Inhibits (suppresses PEPCK, fructose-1,6-bisphosphatase, glucose-6-phosphatase)"],
["Lipogenesis", "Stimulates (activates acetyl-CoA carboxylase, fatty acid synthase)"],
["Lipolysis", "Inhibits (inhibits hormone-sensitive lipase)"],
["Proteolysis", "Inhibits; promotes protein synthesis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(Spacer(1, 6))
story.append(P("<b>Counter-regulatory hormones:</b> glucagon (stimulates glycogenolysis/gluconeogenesis via cAMP/PKA), epinephrine, cortisol, growth hormone — all raise blood glucose, opposing insulin."))
story.append(PageBreak())
# ---------- 2. Diagnosis ----------
story.append(section(2, "Diagnosis of Diabetes Mellitus — Tests, Markers, Values"))
story.append(P("Diagnostic criteria (ADA/WHO) — any one confirmed on two occasions (unless unequivocal hyperglycemia with symptoms):"))
story.append(make_table(
["Test", "Normal", "Prediabetes", "Diabetes"],
[
["Fasting Plasma Glucose (FPG)", "<100 mg/dL (5.6 mmol/L)", "100–125 mg/dL", "≥126 mg/dL (7.0 mmol/L)"],
["2-hr OGTT (75g glucose load)", "<140 mg/dL", "140–199 mg/dL", "≥200 mg/dL (11.1 mmol/L)"],
["HbA1c", "<5.7%", "5.7–6.4%", "≥6.5%"],
["Random Plasma Glucose + symptoms", "-", "-", "≥200 mg/dL"],
],
col_widths=[6*cm, 3.5*cm, 3.5*cm, 3.5*cm]
))
story.append(Spacer(1, 8))
story.append(sub("Gestational Diabetes Screening"))
story.append(P("24–28 weeks gestation, 75g OGTT (one-step): fasting ≥92, 1-hr ≥180, 2-hr ≥153 mg/dL (any one abnormal = GDM); or two-step approach with 50g screen followed by 100g OGTT."))
story.append(sub("Classification Markers"))
story.append(bullets([
"<b>Type 1 DM:</b> autoantibodies — GAD65, islet cell antibodies (ICA), IA-2 (insulinoma-associated antigen 2), insulin autoantibodies (IAA), ZnT8 antibodies. Low/absent C-peptide.",
"<b>Type 2 DM:</b> normal/high C-peptide (insulin resistance), no autoantibodies, associated with obesity/metabolic syndrome.",
"<b>MODY:</b> genetic (e.g., HNF1A, GCK mutations), autosomal dominant, young onset without autoimmunity.",
]))
story.append(sub("Other Markers"))
story.append(bullets([
"Urine glucose (glucosuria — renal threshold ~180 mg/dL).",
"Urine/serum ketones — diabetic ketoacidosis (Type 1).",
"Microalbuminuria (30–300 mg/24h) — early nephropathy marker.",
"C-peptide — differentiates endogenous vs exogenous insulin, assesses beta cell reserve.",
]))
story.append(PageBreak())
# ---------- 3. Pharmacology ----------
story.append(section(3, "Pharmacological Drugs — Classification and Receptors"))
story.append(make_table(
["Class", "Examples", "Mechanism / Receptor Target", "Key Side Effects"],
[
["Biguanides", "Metformin", "Activates AMPK; decreases hepatic gluconeogenesis, increases peripheral insulin sensitivity", "GI upset, lactic acidosis (rare), B12 deficiency"],
["Sulfonylureas", "Glibenclamide, Glipizide, Glimepiride", "Bind SUR1 subunit of K_ATP channel on beta cells → closes channel → insulin release", "Hypoglycemia, weight gain"],
["Meglitinides", "Repaglinide, Nateglinide", "Same K_ATP/SUR1 site, faster/shorter action", "Hypoglycemia (less than SU)"],
["Thiazolidinediones (TZDs)", "Pioglitazone, Rosiglitazone", "Activate PPAR-gamma nuclear receptor → improves insulin sensitivity in adipose/muscle", "Weight gain, fluid retention, heart failure risk, fracture risk"],
["Alpha-glucosidase inhibitors", "Acarbose, Miglitol", "Inhibit intestinal alpha-glucosidase → delay carbohydrate absorption", "Flatulence, GI upset"],
["DPP-4 inhibitors (gliptins)", "Sitagliptin, Vildagliptin, Linagliptin", "Inhibit dipeptidyl peptidase-4 → increases endogenous GLP-1/GIP levels", "Generally well tolerated; pancreatitis risk (rare)"],
["GLP-1 receptor agonists", "Exenatide, Liraglutide, Semaglutide, Dulaglutide", "Agonists at GLP-1 receptor → glucose-dependent insulin secretion, decreases glucagon, delays gastric emptying, satiety", "Nausea, vomiting, pancreatitis risk"],
["SGLT2 inhibitors", "Empagliflozin, Dapagliflozin, Canagliflozin", "Inhibit sodium-glucose cotransporter 2 in proximal renal tubule → glucosuria", "UTI, genital mycotic infections, euglycemic DKA"],
["Amylin analogs", "Pramlintide", "Mimics amylin, co-secreted with insulin — slows gastric emptying, suppresses glucagon", "Nausea, hypoglycemia (with insulin)"],
["Insulin", "See Section 4", "Insulin receptor (tyrosine kinase)", "Hypoglycemia, weight gain"],
],
col_widths=[3.4*cm, 3.6*cm, 6.8*cm, 2.7*cm]
))
story.append(PageBreak())
# ---------- 4. Insulin types ----------
story.append(section(4, "Types of Insulin Supplements"))
story.append(make_table(
["Type", "Examples", "Onset", "Peak", "Duration"],
[
["Rapid-acting", "Lispro, Aspart, Glulisine", "10–15 min", "1–2 hr", "3–5 hr"],
["Short-acting (Regular)", "Regular human insulin", "30–60 min", "2–3 hr", "5–8 hr"],
["Intermediate-acting", "NPH (isophane)", "2–4 hr", "4–10 hr", "10–16 hr"],
["Long-acting", "Glargine, Detemir", "1–2 hr", "minimal peak", "20–24 hr"],
["Ultra-long-acting", "Degludec", "30–90 min", "minimal peak", "up to 42 hr"],
["Premixed", "70/30 NPH/Regular, 75/25 lispro protamine/lispro", "Combination profile", "Combination", "Combination"],
],
col_widths=[3.7*cm, 5.8*cm, 2.6*cm, 2.6*cm, 2.6*cm]
))
story.append(Spacer(1, 8))
story.append(P("<b>Clinical use:</b> rapid-acting insulin is used for prandial control (given with meals); long-acting/basal insulin provides background coverage; premixed formulations offer simplified regimens for select patients."))
story.append(PageBreak())
# ---------- 5. Retinopathy ----------
story.append(section(5, "Diabetic Retinopathy"))
story.append(bullets([
"<b>Pathophysiology:</b> chronic hyperglycemia → pericyte loss, basement membrane thickening, microvascular occlusion and leakage → retinal ischemia and increased VEGF.",
"<b>Non-proliferative diabetic retinopathy (NPDR):</b> microaneurysms, dot-blot hemorrhages, hard exudates, cotton wool spots (retinal ischemia/nerve fiber layer infarcts), venous beading.",
"<b>Proliferative diabetic retinopathy (PDR):</b> neovascularization (retina/disc), vitreous hemorrhage, tractional retinal detachment.",
"<b>Diabetic macular edema:</b> can occur at any stage; leading cause of vision loss.",
"<b>Diagnosis:</b> dilated fundoscopic exam, fundus fluorescein angiography, OCT (optical coherence tomography) for macular edema.",
"<b>Management:</b> glycemic and BP control, laser photocoagulation (panretinal for PDR, focal/grid for macular edema), anti-VEGF intravitreal injections (ranibizumab, bevacizumab, aflibercept), vitrectomy for advanced disease.",
]))
story.append(PageBreak())
# ---------- 6. Nephropathy ----------
story.append(section(6, "Diabetic Nephropathy"))
story.append(bullets([
"<b>Pathophysiology:</b> glomerular hyperfiltration (early) → mesangial matrix expansion → glomerular basement membrane thickening → <b>Kimmelstiel-Wilson nodules</b> (nodular glomerulosclerosis, pathognomonic) → progressive glomerulosclerosis.",
"<b>Stages:</b> hyperfiltration → microalbuminuria (30–300 mg/24h) → overt/macroalbuminuria (>300 mg/24h) → declining GFR → ESRD.",
"<b>Screening:</b> annual urine albumin-to-creatinine ratio (ACR) and eGFR, starting at diagnosis (T2DM) or 5 years post-diagnosis (T1DM).",
"<b>Management:</b> strict glycemic control, BP control (target <130/80), ACE inhibitors/ARBs (reduce intraglomerular pressure), SGLT2 inhibitors (proven renal protective effect independent of glycemic control), protein restriction in advanced CKD.",
]))
story.append(PageBreak())
# ---------- 7. Diabetic foot ----------
story.append(section(7, "Diabetic Foot"))
story.append(bullets([
"<b>Pathophysiology:</b> triad of (1) peripheral neuropathy (sensory loss = loss of protective sensation, motor neuropathy = foot deformity, autonomic neuropathy = dry skin/reduced sweating), (2) peripheral arterial disease (macrovascular ischemia), (3) immunopathy (impaired leukocyte function → susceptibility to infection).",
"<b>Clinical features:</b> painless ulcers (typically over pressure points — metatarsal heads, heel), callus formation, <b>Charcot foot</b> (neuropathic joint destruction, rocker-bottom deformity), gangrene.",
"<b>Classification:</b> Wagner classification (grade 0–5, based on depth/tissue loss/gangrene) or University of Texas classification (grade + stage for infection/ischemia).",
"<b>Diagnosis:</b> 10g Semmes-Weinstein monofilament testing, vibration perception (biothesiometer), ankle-brachial index (ABI) for arterial disease, probe-to-bone test for osteomyelitis, imaging (X-ray/MRI).",
"<b>Management:</b> regular foot inspection, offloading devices, wound debridement, infection control (antibiotics), revascularization if ischemic, patient education, appropriate footwear.",
]))
story.append(PageBreak())
# ---------- 8. Cardiac ----------
story.append(section(8, "Cardiac Associations of Diabetes Mellitus"))
story.append(bullets([
"<b>Accelerated atherosclerosis:</b> hyperglycemia, dyslipidemia, and insulin resistance promote endothelial dysfunction, advanced glycation end-products (AGEs), and inflammation → accelerated coronary artery disease.",
"<b>Diabetic cardiomyopathy:</b> myocardial dysfunction independent of coronary disease/hypertension, driven by lipotoxicity, myocardial fibrosis, mitochondrial dysfunction, and AGE cross-linking — manifests as diastolic dysfunction progressing to heart failure.",
"<b>Silent myocardial ischemia:</b> autonomic neuropathy blunts anginal pain perception → higher risk of unrecognized MI.",
"<b>Autonomic neuropathy:</b> resting tachycardia, orthostatic hypotension, reduced heart rate variability.",
"<b>Heart failure:</b> diabetics have 2–4x increased risk of heart failure (both HFrEF and HFpEF).",
"<b>Management:</b> aggressive risk factor control (statins, BP control), SGLT2 inhibitors (proven cardiovascular/heart failure benefit), GLP-1 receptor agonists (proven MACE reduction), antiplatelet therapy where indicated.",
]))
story.append(PageBreak())
# ---------- 9. NAFLD ----------
story.append(section(9, "Non-Alcoholic Fatty Liver Disease (NAFLD)"))
story.append(bullets([
"<b>Link to diabetes:</b> insulin resistance drives increased hepatic free fatty acid delivery and de novo lipogenesis → hepatic triglyceride accumulation (steatosis); lipotoxicity and oxidative stress can progress disease.",
"<b>Spectrum:</b> simple steatosis (NAFL) → non-alcoholic steatohepatitis (NASH) (steatosis + inflammation + hepatocyte injury/ballooning) → fibrosis → cirrhosis → hepatocellular carcinoma risk.",
"<b>Diagnosis:</b> elevated ALT/AST (often ALT>AST, mild elevation), ultrasound/imaging showing hepatic steatosis, non-invasive fibrosis scores (FIB-4, NAFLD fibrosis score), transient elastography (FibroScan), liver biopsy (gold standard for NASH/fibrosis staging).",
"<b>Management:</b> weight loss (7–10% body weight), glycemic control, pioglitazone (improves histology in NASH), GLP-1 receptor agonists (weight loss and possible hepatic benefit), avoid alcohol, manage dyslipidemia.",
]))
story.append(PageBreak())
# ---------- 10. IDM ----------
story.append(section(10, "Infant of a Diabetic Mother (IDM)"))
story.append(sub("Pathophysiology — Pedersen Hypothesis"))
story.append(P("Maternal hyperglycemia → crosses placenta → fetal hyperglycemia → fetal beta-cell hyperplasia → <b>fetal hyperinsulinemia</b> → drives fetal growth and multiple neonatal complications."))
story.append(sub("Complications"))
story.append(bullets([
"<b>Macrosomia</b> (insulin as a growth factor, particularly increased fat/muscle) → risk of birth trauma, shoulder dystocia, C-section.",
"<b>Neonatal hypoglycemia</b> — after delivery, maternal glucose supply stops but fetal hyperinsulinemia persists transiently → risk of profound hypoglycemia in first hours of life.",
"<b>Respiratory distress syndrome</b> — insulin antagonizes cortisol's effect on surfactant maturation → delayed lung maturity.",
"<b>Congenital malformations</b> (associated with poor glycemic control in first trimester, organogenesis period): cardiac defects (transposition of great vessels, VSD), neural tube defects, <b>caudal regression syndrome</b> (classically associated with maternal diabetes).",
"<b>Polycythemia</b> (from chronic fetal hypoxia/erythropoietin response), <b>hyperbilirubinemia</b> (from polycythemia breakdown), <b>hypocalcemia</b>, <b>hypomagnesemia</b>.",
"Hypertrophic cardiomyopathy (transient, from hyperinsulinemia).",
]))
story.append(sub("Management"))
story.append(bullets([
"Close neonatal glucose monitoring in first 24–48 hours.",
"Early feeding; treatment of hypoglycemia (IV dextrose if symptomatic/severe).",
"Monitoring for respiratory distress.",
"Echocardiogram if cardiac concerns.",
"Phototherapy for significant hyperbilirubinemia.",
]))
story.append(Spacer(1, 20))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#B0B0B0")))
story.append(Spacer(1, 6))
story.append(Paragraph(
"<i>This study guide is compiled from standard medical education content for exam preparation purposes. "
"Always verify current clinical guidelines and drug dosing against up-to-date primary sources before clinical application.</i>",
styles["Body"]
))
def add_page_number(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.setFillColor(colors.grey)
canvas.drawCentredString(A4[0] / 2, 1.2 * cm, f"Page {doc.page} | Diabetes Mellitus Study Guide")
canvas.restoreState()
doc = SimpleDocTemplate(
OUT, pagesize=A4,
topMargin=1.8*cm, bottomMargin=1.8*cm, leftMargin=1.8*cm, rightMargin=1.8*cm,
title="Diabetes Mellitus Study Guide"
)
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
print("PDF written to", OUT)
cd /tmp/workspace/diabetes-study-guide && python3 build_pdf.py
ls -la /tmp/workspace/diabetes-study-guide/
Diabetes Mellitus Study Guide
PDF Document · PDF
Can you include flow charts for insulin formation and glucose metabolism. And can you also add signs and images for retinopathies and other eye related issues. Detailed explain the NAFLD. And IDM, what are the complications to the mother and fetus, how to treat the mother , pregnancy female and the fetus and then the baby. Add these things to the pdf
diabetic retinopathy fundus photograph microaneurysms and dot-blot hemorrhages
proliferative diabetic retinopathy neovascularization fundus

This clinical photograph shows a side-by-side comparison of two fundus images (A and B) illustrating the progression of diabetic retinopathy. Image A depicts Non-Proliferative Diabetic Retinopathy (NPDR), characterized by a relatively stable retinal vascular structure with early clinical signs, including isolated retinal hemorrhages and a distinct white cotton wool spot located superior to the macula. Image B illustrates Proliferative Diabetic Retinopathy (PDR), demonstrating advanced disease manifestations. Key visible features in Image B include extensive neovascularization (neovessels) originating from the optic disc, characterized by disorganized and atypical vascular branching. The retinal background in Image B shows widespread pathology with numerous yellow-white hard exudates and significant macular exudation, indicating a breakdown of the blood-retinal barrier and chronic ischemia. These images serve as an educational comparison between the non-proliferative stage and the high-risk proliferative stage of diabetic eye disease, highlighting diagnostic landmarks such as neovascularization and exudative changes.

A multi-panel medical image illustrating the clinical manifestations and progression of diabetic retinopathy using fundus photography and Optical Coherence Tomography (OCT). Panel A displays a color fundus photograph of the posterior pole showing microaneurysms and dot hemorrhages indicative of diabetic maculopathy. Panel B highlights clinically significant macular edema (CSME) with visible hard exudates (B1). Panel C provides corresponding OCT imaging, including a retinal thickness heat map and a cross-sectional scan showing intraretinal fluid. Panels D and E are widefield fundus photographs demonstrating advanced proliferative diabetic retinopathy (PDR). Key pathological features identified with numbered arrows include cotton wool spots (D1), venous beading (D2), intraretinal microvascular abnormalities (IRMA) (D3/E1), neovascularization at the disc (D4), and venous loops (D5). Panel E further illustrates end-stage complications and treatment, showing laser photocoagulation scars (E2), retinal neovascularization (E3), pre-retinal hemorrhage (E4), blot hemorrhage (E5), and vitreous hemorrhage (E6). This compilation serves as an educational tool for identifying the transition from non-proliferative to proliferative diabetic disease.

A multi-panel ophthalmological image set displaying eight photographs (a-h) that illustrate the progression of Diabetic Retinopathy (DR). The set includes color fundus photographs and Fluorescein Angiography (FA) images. (a) Moderate Non-Proliferative Diabetic Retinopathy (NPDR) with scattered microaneurysms. (b) Severe NPDR showing intraretinal hemorrhages and hard exudates. (c) Corresponding FA for severe NPDR highlighting hyperfluorescent microaneurysms. (d) Early Proliferative Diabetic Retinopathy (PDR) with prominent circinate exudates and cotton-wool spots. (e) FA of early PDR demonstrating focal leakage and early neovascularization at the disc (NVD). (f) High-risk PDR with visible vitreous haze and vascular tortuosity. (g) FA for high-risk PDR showing extensive leakage from neovascularization and areas of capillary non-perfusion (ischemia). (h) Advanced Diabetic Eye Disease (ADED) characterized by fibrovascular proliferation, tractional retinal changes, and significant obscuration of the optic disc and retinal landmarks. This collection serves as a comparative diagnostic tool for identifying vascular leakage, retinal ischemia, and proliferative changes across different clinical stages of diabetic eye disease.

This diagnostic image set consists of five fundus fluorescein angiography (FA) images (a–e) demonstrating the progression of diabetic retinopathy (DR). (a) Normal: Displays a healthy retinal vascular pattern with a clear macula and well-defined optic disc. (b) Background Diabetic Retinopathy (BDR): Highlights early microvascular changes, with a red circle indicating hyperfluorescent microaneurysms. (c) Pre-proliferative Diabetic Retinopathy (PPDR): Shows significant capillary non-perfusion, characterized by extensive areas of hypofluorescence (dark zones) where microvessels have dropped out. (d) Early Proliferative Diabetic Retinopathy (PDR): Features early neovascularization, with a red circle highlighting tufts of hypervascularization on the retina or disc. (e) Late PDR: Demonstrates advanced disease where active leakage from fragile new vascular tissue causes diffuse, high-intensity hyperfluorescent staining (indicated by a red circle). The series illustrates key pathological markers used in ophthalmology for staging DR, including microangiomas, ischemia, and neovascularization, emphasizing the clinical significance of FA in identifying vascular leakage and non-perfusion.
diabetic macular edema optical coherence tomography OCT

A three-part composite diagnostic image showing Spectral Domain Optical Coherence Tomography (SD-OCT) findings for Diabetic Macular Edema (DME). Panel (a) presents a horizontal cross-sectional OCT B-scan demonstrating significant foveal thickening with intraretinal cystic spaces and altered reflectivity, highlighted by a yellow arrow, indicating cystoid macular edema. Panel (b) shows a 6x6 mm macular cube thickness overlay map; the color scale (green to red) indicates topographic retinal thickness, with a large central red/white area signifying severe thickening exceeding 500 µm. Panel (c) displays an Early Treatment Diabetic Retinopathy Study (ETDRS) grid map providing quantitative data. A red arrow points to the central subfield, which shows a significantly elevated retinal thickness of 638 µm. This clinical visual illustrates the diagnostic hallmarks used in ophthalmology to assess the severity of diabetic retinopathy and macular fluid accumulation.

This diagnostic image is an Optical Coherence Tomography (OCT) cross-sectional scan of the human retina, illustrating classic features of Diabetic Macular Edema (DME). The scan shows the characteristic anatomical layers of the retina, with a prominent hyperreflective band at the base representing the retinal pigment epithelium (RPE) and Bruch's membrane complex. The primary pathological finding is significant retinal thickening and distortion of the foveal contour. Within the inner and middle retinal layers, multiple hyporeflective, cyst-like spaces are visible, representing intraretinal fluid accumulation (cystoid macular edema). These cystic spaces vary in size and shape, causing displacement and architectural disruption of the surrounding neurosensory retinal tissue. The image is a critical educational tool for ophthalmology, demonstrating the diagnostic utility of OCT in identifying and monitoring macular edema resulting from diabetic retinopathy.

A comparison of five cross-sectional Spectral Domain Optical Coherence Tomography (OCT) scans of the macula, illustrating the structural progression of diabetic retinopathy (DR). (A) Normal retina with a clear foveal depression and intact stratified layers. (B) Early changes in a diabetic patient showing altered reflectivity and subtle layer thickening without overt edema. (C) Mild non-proliferative diabetic retinopathy (NPDR) exhibiting a focal cystic space within the inner retinal layers at the fovea. (D) Severe NPDR characterized by significant diabetic macular edema (DME), visible as a large hyporeflective subretinal fluid pocket and diffuse intraretinal thickening. (E) Proliferative diabetic retinopathy (PDR) demonstrating a large intraretinal cyst, hyperreflective foci representing lipid exudates in the temporal macula, and inner retinal thinning suggestive of macular ischemia. The series highlights key diagnostic features including macular edema, subretinal fluid, hard exudates, and neurosensory architectural distortion.
infant of diabetic mother macrosomia neonatal
mkdir -p /tmp/workspace/diabetes-study-guide/images && cd /tmp/workspace/diabetes-study-guide/images && \ curl -sL -o npdr_pdr_compare.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_2be7acb9c280d151e627d68e4d67db96939457ea08afa1591c71079c3124df10.jpg" && \ curl -sL -o dr_progression_multipanel.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_11fce460ab92b396a501a2e6e961014e77f6ce88252a6d0e96fa94b56c26ca5c.jpg" && \ curl -sL -o dr_fa_progression.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_633087b66ecedb67128377f2a64a1f5128010817500c31611926c4b716c7923d.jpg" && \ curl -sL -o dme_oct_scan.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_0ef69763407fdb8c37908f5e83920636752f56a23867f6b355003018f4f70676.jpg" && \ curl -sL -o dme_oct_progression.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_69d9f43e87a21b7cb607dc278c219af9decbcf31bbc497c1380be2ff80cdb122.jpg" && \ curl -sL -o ocular_pathology_compare.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_4bd236109668526070c698c92b7cc4350e2df49e12f7b7f525df047f3fa4f427.jpg" && \ ls -la
~/diabetes-study-guide/make_flowcharts.py
#!/usr/bin/env python3
"""Generate flowchart diagrams for insulin formation and glucose metabolism using matplotlib."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
import os
OUTDIR = "/tmp/workspace/diabetes-study-guide/images"
os.makedirs(OUTDIR, exist_ok=True)
BLUE = "#1a3d5c"
LIGHT = "#EEF3F7"
GREEN = "#2e7d32"
ORANGE = "#c0622a"
def box(ax, x, y, w, h, text, fc=LIGHT, ec=BLUE, fontsize=9.5, fontcolor="black", weight="normal"):
b = FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.08",
linewidth=1.4, edgecolor=ec, facecolor=fc)
ax.add_patch(b)
ax.text(x + w/2, y + h/2, text, ha="center", va="center", fontsize=fontsize,
color=fontcolor, weight=weight, wrap=True)
def arrow(ax, x1, y1, x2, y2, color=BLUE):
a = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle="-|>", mutation_scale=16,
linewidth=1.6, color=color)
ax.add_patch(a)
# ---------------------------------------------------------------
# FLOWCHART 1: Insulin Formation (Biosynthesis pathway)
# ---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(9, 11))
ax.set_xlim(0, 10)
ax.set_ylim(0, 22)
ax.axis("off")
ax.set_title("Insulin Formation (Biosynthesis in the Pancreatic Beta Cell)", fontsize=13, weight="bold", color=BLUE, pad=14)
steps = [
"INSULIN GENE (Chromosome 11)\nTranscription in beta-cell nucleus",
"mRNA\nTranslated on rough ER ribosomes",
"PREPROINSULIN\n(signal peptide + B-chain + C-peptide + A-chain)",
"Signal peptide cleaved in ER lumen",
"PROINSULIN\n(single chain: B-chain - C-peptide - A-chain,\nfolded with 2 disulfide bonds)",
"Transported to Golgi apparatus\nPackaged into immature secretory granules",
"Cleavage by Prohormone Convertases\n(PC1/3, PC2) + Carboxypeptidase E",
"MATURE INSULIN (A-chain + B-chain, disulfide-linked)\n+ C-PEPTIDE (released in EQUIMOLAR amounts)",
"Stored in mature secretory granules\nawaiting glucose-triggered exocytosis",
]
n = len(steps)
top = 20.5
gap = 2.35
h = 1.7
w = 8.6
x0 = 0.7
for i, s in enumerate(steps):
y = top - i * gap
fc = LIGHT
fontcolor = "black"
if i == 2 or i == 4:
fc = "#D6E4EF"
if i == 7:
fc = BLUE
fontcolor = "white"
box(ax, x0, y, w, h, s, fc=fc, fontcolor=fontcolor, weight="bold" if i in (0,2,4,7) else "normal")
if i < n - 1:
arrow(ax, x0 + w/2, y, x0 + w/2, y - (gap - h))
plt.tight_layout()
plt.savefig(f"{OUTDIR}/flowchart_insulin_formation.png", dpi=180, bbox_inches="tight")
plt.close()
# ---------------------------------------------------------------
# FLOWCHART 2: Glucose-triggered Insulin Secretion (Beta cell)
# ---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(9, 11))
ax.set_xlim(0, 10)
ax.set_ylim(0, 22)
ax.axis("off")
ax.set_title("Glucose-Triggered Insulin Secretion (Pancreatic Beta Cell)", fontsize=13, weight="bold", color=BLUE, pad=14)
steps2 = [
"Rise in blood GLUCOSE",
"Glucose enters beta cell via GLUT2 transporter",
"GLUCOKINASE phosphorylates glucose\n(rate-limiting 'glucose sensor' step)",
"Glycolysis + oxidative metabolism\n\u2191 ATP : ADP ratio",
"ATP-sensitive K+ channel (K-ATP: SUR1/Kir6.2) CLOSES",
"Membrane DEPOLARIZATION",
"Voltage-gated Ca2+ channels OPEN\n\u2192 Ca2+ influx",
"Exocytosis of insulin secretory granules",
"INSULIN + C-PEPTIDE released into blood\n(biphasic: rapid 1st phase + sustained 2nd phase)",
]
n2 = len(steps2)
for i, s in enumerate(steps2):
y = top - i * gap
fc = LIGHT
fontcolor = "black"
weight = "normal"
if i == 0:
fc = ORANGE; fontcolor = "white"; weight = "bold"
if i == 4 or i == 6:
fc = "#D6E4EF"; weight = "bold"
if i == 8:
fc = BLUE; fontcolor = "white"; weight = "bold"
box(ax, x0, y, w, h, s, fc=fc, fontcolor=fontcolor, weight=weight)
if i < n2 - 1:
arrow(ax, x0 + w/2, y, x0 + w/2, y - (gap - h))
plt.tight_layout()
plt.savefig(f"{OUTDIR}/flowchart_insulin_secretion.png", dpi=180, bbox_inches="tight")
plt.close()
# ---------------------------------------------------------------
# FLOWCHART 3: Insulin Signaling and Glucose Metabolism (target cell)
# ---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(10, 12))
ax.set_xlim(0, 12)
ax.set_ylim(0, 16)
ax.axis("off")
ax.set_title("Insulin Signaling Pathway and Effects on Glucose Metabolism\n(Muscle / Adipose / Liver)", fontsize=13, weight="bold", color=BLUE, pad=14)
# top chain
box(ax, 3.7, 14.0, 4.6, 1.3, "INSULIN binds\nINSULIN RECEPTOR (tyrosine kinase)", fc=BLUE, fontcolor="white", weight="bold")
arrow(ax, 6.0, 14.0, 6.0, 12.9)
box(ax, 3.7, 11.6, 4.6, 1.3, "Receptor autophosphorylation\n\u2192 activates IRS-1 / IRS-2", fc=LIGHT, weight="bold")
arrow(ax, 6.0, 11.6, 6.0, 10.5)
box(ax, 3.7, 9.2, 4.6, 1.3, "PI3K \u2192 Akt (PKB) activation", fc="#D6E4EF", weight="bold")
arrow(ax, 6.0, 9.2, 6.0, 8.1)
box(ax, 3.7, 6.8, 4.6, 1.3, "GLUT4 translocation to cell membrane", fc=LIGHT, weight="bold")
arrow(ax, 6.0, 6.8, 6.0, 5.7)
box(ax, 3.7, 4.4, 4.6, 1.3, "GLUCOSE UPTAKE into cell", fc=GREEN, fontcolor="white", weight="bold")
# side branch - Ras/MAPK
arrow(ax, 8.3, 12.25, 9.6, 12.25, color=ORANGE)
box(ax, 9.6, 11.6, 2.2, 1.3, "Ras/MAPK\npathway\n(growth effects)", fc="#FBE7DA", ec=ORANGE, fontsize=8.5)
# downstream metabolic effects branching from glucose uptake / Akt
arrow(ax, 3.7, 5.05, 1.6, 5.05, color=BLUE)
metab_boxes = [
(0.2, 3.0, "\u2191 GLYCOLYSIS\n(\u2191hexokinase, PFK-1,\npyruvate kinase)"),
(0.2, 1.1, "\u2191 GLYCOGENESIS\n(activates glycogen\nsynthase)"),
]
box(ax, 0.2, 5.6, 3.0, 1.1, "Stimulatory effects", fc=GREEN, fontcolor="white", fontsize=9, weight="bold")
arrow(ax, 1.7, 5.6, 1.7, 4.1)
box(ax, 0.2, 3.0, 3.0, 1.1, "\u2191 Glycolysis\n(hexokinase, PFK-1, pyruvate kinase)", fontsize=8.3)
arrow(ax, 1.7, 3.0, 1.7, 2.1)
box(ax, 0.2, 0.9, 3.0, 1.1, "\u2191 Glycogenesis (glycogen synthase)\n\u2191 Lipogenesis (ACC, FAS)", fontsize=8.3)
arrow(ax, 8.3, 5.05, 10.4, 5.05, color=ORANGE)
box(ax, 8.4, 5.6, 3.4, 1.1, "Inhibitory effects", fc=ORANGE, fontcolor="white", fontsize=9, weight="bold")
arrow(ax, 10.1, 5.6, 10.1, 4.1)
box(ax, 8.4, 3.0, 3.4, 1.1, "\u2193 Gluconeogenesis\n(\u2193PEPCK, F1,6BPase, G6Pase)", fontsize=8.3)
arrow(ax, 10.1, 3.0, 10.1, 2.1)
box(ax, 8.4, 0.9, 3.4, 1.1, "\u2193 Glycogenolysis\n\u2193 Lipolysis (\u2193HSL) \u2193 Proteolysis", fontsize=8.3)
plt.tight_layout()
plt.savefig(f"{OUTDIR}/flowchart_insulin_signaling.png", dpi=180, bbox_inches="tight")
plt.close()
print("Flowcharts generated successfully in", OUTDIR)
cd /tmp/workspace/diabetes-study-guide && python3 make_flowcharts.py && ls -la images/
~/diabetes-study-guide/build_pdf.py
#!/usr/bin/env python3
"""Build the Diabetes Mellitus Study Guide PDF - v2 (flowcharts, eye images, expanded NAFLD & IDM)."""
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
PageBreak, ListFlowable, ListItem, HRFlowable, Image
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from PIL import Image as PILImage
BASE = "/tmp/workspace/diabetes-study-guide"
IMG = f"{BASE}/images"
OUT = f"{BASE}/Diabetes_Mellitus_Study_Guide.pdf"
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="TitleBig", fontSize=24, leading=28, alignment=TA_CENTER,
textColor=colors.HexColor("#1a3d5c"), spaceAfter=6, fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Subtitle", fontSize=13, leading=16, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), spaceAfter=20, fontName="Helvetica"))
styles.add(ParagraphStyle(name="SectionHeading", fontSize=16, leading=20, spaceBefore=14, spaceAfter=8,
textColor=colors.white, backColor=colors.HexColor("#1a3d5c"),
fontName="Helvetica-Bold", leftIndent=6, borderPadding=6))
styles.add(ParagraphStyle(name="SubHeading", fontSize=12.5, leading=15, spaceBefore=10, spaceAfter=4,
textColor=colors.HexColor("#1a3d5c"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="SubSubHeading", fontSize=11, leading=13, spaceBefore=8, spaceAfter=3,
textColor=colors.HexColor("#c0622a"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Body", fontSize=10, leading=14, spaceAfter=4, alignment=TA_LEFT, fontName="Helvetica"))
styles.add(ParagraphStyle(name="BulletBody", fontSize=10, leading=13.5, spaceAfter=2, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TOCItem", fontSize=11, leading=18, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableCell", fontSize=8.7, leading=11, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableHeader", fontSize=9, leading=11, fontName="Helvetica-Bold", textColor=colors.white))
styles.add(ParagraphStyle(name="Caption", fontSize=8.5, leading=10.5, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), fontName="Helvetica-Oblique", spaceAfter=10))
def P(text):
return Paragraph(text, styles["Body"])
def bullets(items):
return ListFlowable(
[ListItem(Paragraph(i, styles["BulletBody"]), leftIndent=6) for i in items],
bulletType="bullet", start="•", leftIndent=14, spaceBefore=2, spaceAfter=6
)
def make_table(header, rows, col_widths=None):
data = [[Paragraph(h, styles["TableHeader"]) for h in header]]
for r in rows:
data.append([Paragraph(str(c), styles["TableCell"]) for c in r])
t = Table(data, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1a3d5c")),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#B0B0B0")),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#EEF3F7")]),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]))
return t
def section(num, title):
return Paragraph(f"{num}. {title}", styles["SectionHeading"])
def sub(title):
return Paragraph(title, styles["SubHeading"])
def subsub(title):
return Paragraph(title, styles["SubSubHeading"])
def fig(path, max_width_cm=16.5, caption=None):
im = PILImage.open(path)
w, h = im.size
max_w = max_width_cm * cm
scale = max_w / w
max_h = 21 * cm # safety cap
disp_w = max_w
disp_h = h * scale
if disp_h > max_h:
disp_h = max_h
disp_w = w * (max_h / h)
flow = [Image(path, width=disp_w, height=disp_h)]
if caption:
flow.append(Paragraph(caption, styles["Caption"]))
return flow
story = []
# ---------- Cover ----------
story.append(Spacer(1, 3.2 * cm))
story.append(Paragraph("Diabetes Mellitus", styles["TitleBig"]))
story.append(Paragraph("Complete Study Guide", styles["TitleBig"]))
story.append(Paragraph("Biochemistry · Diagnosis · Pharmacology · Complications · Special Populations", styles["Subtitle"]))
story.append(Spacer(1, 1*cm))
story.append(HRFlowable(width="80%", thickness=1, color=colors.HexColor("#1a3d5c"), hAlign="CENTER"))
story.append(Spacer(1, 1*cm))
toc_items = [
"1. Biochemistry of Insulin Formation and Glucose Metabolism (with flowcharts)",
"2. Diagnosis of Diabetes Mellitus — Tests, Markers, Values",
"3. Pharmacological Drugs — Classification and Receptors",
"4. Types of Insulin Supplements",
"5. Diabetic Retinopathy and Other Diabetic Eye Disease (with images)",
"6. Diabetic Nephropathy",
"7. Diabetic Foot",
"8. Cardiac Associations of Diabetes Mellitus",
"9. Non-Alcoholic Fatty Liver Disease (NAFLD) — Detailed",
"10. Infant of a Diabetic Mother (IDM) — Maternal & Fetal Complications and Management",
]
story.append(Paragraph("Contents (Correct Study Order)", styles["SubHeading"]))
for item in toc_items:
story.append(Paragraph(item, styles["TOCItem"]))
story.append(PageBreak())
# ============================================================
# 1. BIOCHEMISTRY (with flowcharts)
# ============================================================
story.append(section(1, "Biochemistry of Insulin Formation and Glucose Metabolism"))
story.append(sub("Insulin Synthesis"))
story.append(bullets([
"Insulin gene (chromosome 11) transcribed in pancreatic beta cells → mRNA translated into <b>preproinsulin</b> on rough ER ribosomes.",
"Signal peptide cleaved → <b>proinsulin</b> (single chain: A-chain, B-chain, connecting C-peptide, held by 2 disulfide bonds).",
"Proinsulin transported to Golgi, packaged into secretory granules, cleaved by prohormone convertases (PC1/3, PC2) and carboxypeptidase E → <b>insulin (A+B chains linked by disulfide bonds) + C-peptide</b> in equimolar amounts.",
"C-peptide has no known metabolic activity but is a useful clinical marker of endogenous insulin production (unaffected by exogenous insulin injections).",
]))
story.extend(fig(f"{IMG}/flowchart_insulin_formation.png", max_width_cm=11,
caption="Flowchart 1: Insulin biosynthesis pathway from gene transcription to mature hormone."))
story.append(sub("Insulin Secretion Mechanism (Beta Cell)"))
story.append(bullets([
"Glucose enters the beta cell via the <b>GLUT2</b> transporter.",
"Glucokinase phosphorylates glucose (rate-limiting "glucose sensor" step).",
"Glycolysis/oxidative metabolism raises the ATP:ADP ratio.",
"ATP closes <b>ATP-sensitive K+ channels (K<sub>ATP</sub>: SUR1/Kir6.2 subunits)</b> → membrane depolarization.",
"Voltage-gated Ca2+ channels open → Ca2+ influx → triggers exocytosis of insulin granules.",
"Biphasic release: first phase (stored granules, rapid) and second phase (newly synthesized insulin, sustained).",
]))
story.append(PageBreak())
story.extend(fig(f"{IMG}/flowchart_insulin_secretion.png", max_width_cm=11,
caption="Flowchart 2: Glucose-stimulated insulin secretion pathway in the pancreatic beta cell."))
story.append(sub("Insulin Receptor and Signaling"))
story.append(bullets([
"Insulin receptor: tetrameric transmembrane <b>receptor tyrosine kinase</b> (2 alpha + 2 beta subunits).",
"Insulin binding → autophosphorylation of beta subunits → phosphorylates <b>IRS-1/IRS-2</b> → activates <b>PI3K/Akt pathway</b> → triggers <b>GLUT4 translocation</b> to the cell membrane in muscle/adipose tissue → glucose uptake.",
"A parallel <b>Ras/MAPK pathway</b> mediates insulin's growth/mitogenic effects.",
]))
story.append(PageBreak())
story.extend(fig(f"{IMG}/flowchart_insulin_signaling.png", max_width_cm=15,
caption="Flowchart 3: Insulin receptor signal transduction and downstream effects on glucose, glycogen, and lipid metabolism."))
story.append(sub("Glucose Metabolism — Insulin's Actions (Summary Table)"))
story.append(make_table(
["Pathway", "Effect of Insulin"],
[
["Glycolysis", "Stimulates (hexokinase, PFK-1, pyruvate kinase induction)"],
["Glycogenesis", "Stimulates (activates glycogen synthase)"],
["Glycogenolysis", "Inhibits"],
["Gluconeogenesis", "Inhibits (suppresses PEPCK, fructose-1,6-bisphosphatase, glucose-6-phosphatase)"],
["Lipogenesis", "Stimulates (activates acetyl-CoA carboxylase, fatty acid synthase)"],
["Lipolysis", "Inhibits (inhibits hormone-sensitive lipase)"],
["Proteolysis", "Inhibits; promotes protein synthesis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(Spacer(1, 6))
story.append(P("<b>Counter-regulatory hormones:</b> glucagon (stimulates glycogenolysis/gluconeogenesis via cAMP/PKA), epinephrine, cortisol, growth hormone — all raise blood glucose, opposing insulin."))
story.append(PageBreak())
# ============================================================
# 2. DIAGNOSIS
# ============================================================
story.append(section(2, "Diagnosis of Diabetes Mellitus — Tests, Markers, Values"))
story.append(P("Diagnostic criteria (ADA/WHO) — any one confirmed on two occasions (unless unequivocal hyperglycemia with symptoms):"))
story.append(make_table(
["Test", "Normal", "Prediabetes", "Diabetes"],
[
["Fasting Plasma Glucose (FPG)", "<100 mg/dL (5.6 mmol/L)", "100–125 mg/dL", "≥126 mg/dL (7.0 mmol/L)"],
["2-hr OGTT (75g glucose load)", "<140 mg/dL", "140–199 mg/dL", "≥200 mg/dL (11.1 mmol/L)"],
["HbA1c", "<5.7%", "5.7–6.4%", "≥6.5%"],
["Random Plasma Glucose + symptoms", "-", "-", "≥200 mg/dL"],
],
col_widths=[6*cm, 3.5*cm, 3.5*cm, 3.5*cm]
))
story.append(Spacer(1, 8))
story.append(sub("Gestational Diabetes Screening"))
story.append(P("24–28 weeks gestation, 75g OGTT (one-step): fasting ≥92, 1-hr ≥180, 2-hr ≥153 mg/dL (any one abnormal = GDM); or two-step approach with 50g screen followed by 100g OGTT."))
story.append(sub("Classification Markers"))
story.append(bullets([
"<b>Type 1 DM:</b> autoantibodies — GAD65, islet cell antibodies (ICA), IA-2 (insulinoma-associated antigen 2), insulin autoantibodies (IAA), ZnT8 antibodies. Low/absent C-peptide.",
"<b>Type 2 DM:</b> normal/high C-peptide (insulin resistance), no autoantibodies, associated with obesity/metabolic syndrome.",
"<b>MODY:</b> genetic (e.g., HNF1A, GCK mutations), autosomal dominant, young onset without autoimmunity.",
]))
story.append(sub("Other Markers"))
story.append(bullets([
"Urine glucose (glucosuria — renal threshold ~180 mg/dL).",
"Urine/serum ketones — diabetic ketoacidosis (Type 1).",
"Microalbuminuria (30–300 mg/24h) — early nephropathy marker.",
"C-peptide — differentiates endogenous vs exogenous insulin, assesses beta cell reserve.",
]))
story.append(PageBreak())
# ============================================================
# 3. PHARMACOLOGY
# ============================================================
story.append(section(3, "Pharmacological Drugs — Classification and Receptors"))
story.append(make_table(
["Class", "Examples", "Mechanism / Receptor Target", "Key Side Effects"],
[
["Biguanides", "Metformin", "Activates AMPK; decreases hepatic gluconeogenesis, increases peripheral insulin sensitivity", "GI upset, lactic acidosis (rare), B12 deficiency"],
["Sulfonylureas", "Glibenclamide, Glipizide, Glimepiride", "Bind SUR1 subunit of K_ATP channel on beta cells → closes channel → insulin release", "Hypoglycemia, weight gain"],
["Meglitinides", "Repaglinide, Nateglinide", "Same K_ATP/SUR1 site, faster/shorter action", "Hypoglycemia (less than SU)"],
["Thiazolidinediones (TZDs)", "Pioglitazone, Rosiglitazone", "Activate PPAR-gamma nuclear receptor → improves insulin sensitivity in adipose/muscle", "Weight gain, fluid retention, heart failure risk, fracture risk"],
["Alpha-glucosidase inhibitors", "Acarbose, Miglitol", "Inhibit intestinal alpha-glucosidase → delay carbohydrate absorption", "Flatulence, GI upset"],
["DPP-4 inhibitors (gliptins)", "Sitagliptin, Vildagliptin, Linagliptin", "Inhibit dipeptidyl peptidase-4 → increases endogenous GLP-1/GIP levels", "Generally well tolerated; pancreatitis risk (rare)"],
["GLP-1 receptor agonists", "Exenatide, Liraglutide, Semaglutide, Dulaglutide", "Agonists at GLP-1 receptor → glucose-dependent insulin secretion, decreases glucagon, delays gastric emptying, satiety", "Nausea, vomiting, pancreatitis risk"],
["SGLT2 inhibitors", "Empagliflozin, Dapagliflozin, Canagliflozin", "Inhibit sodium-glucose cotransporter 2 in proximal renal tubule → glucosuria", "UTI, genital mycotic infections, euglycemic DKA"],
["Amylin analogs", "Pramlintide", "Mimics amylin, co-secreted with insulin — slows gastric emptying, suppresses glucagon", "Nausea, hypoglycemia (with insulin)"],
["Insulin", "See Section 4", "Insulin receptor (tyrosine kinase)", "Hypoglycemia, weight gain"],
],
col_widths=[3.4*cm, 3.6*cm, 6.8*cm, 2.7*cm]
))
story.append(PageBreak())
# ============================================================
# 4. INSULIN TYPES
# ============================================================
story.append(section(4, "Types of Insulin Supplements"))
story.append(make_table(
["Type", "Examples", "Onset", "Peak", "Duration"],
[
["Rapid-acting", "Lispro, Aspart, Glulisine", "10–15 min", "1–2 hr", "3–5 hr"],
["Short-acting (Regular)", "Regular human insulin", "30–60 min", "2–3 hr", "5–8 hr"],
["Intermediate-acting", "NPH (isophane)", "2–4 hr", "4–10 hr", "10–16 hr"],
["Long-acting", "Glargine, Detemir", "1–2 hr", "minimal peak", "20–24 hr"],
["Ultra-long-acting", "Degludec", "30–90 min", "minimal peak", "up to 42 hr"],
["Premixed", "70/30 NPH/Regular, 75/25 lispro protamine/lispro", "Combination profile", "Combination", "Combination"],
],
col_widths=[3.7*cm, 5.8*cm, 2.6*cm, 2.6*cm, 2.6*cm]
))
story.append(Spacer(1, 8))
story.append(P("<b>Clinical use:</b> rapid-acting insulin is used for prandial control (given with meals); long-acting/basal insulin provides background coverage; premixed formulations offer simplified regimens for select patients."))
story.append(PageBreak())
# ============================================================
# 5. RETINOPATHY + OTHER EYE DISEASE (with images)
# ============================================================
story.append(section(5, "Diabetic Retinopathy and Other Diabetic Eye Disease"))
story.append(sub("Pathophysiology"))
story.append(P("Chronic hyperglycemia causes pericyte loss, thickening of the retinal capillary basement membrane, and microvascular occlusion. The resulting retinal ischemia raises VEGF (vascular endothelial growth factor), which drives leakage and, later, abnormal new vessel growth."))
story.append(sub("Signs — Non-Proliferative Diabetic Retinopathy (NPDR)"))
story.append(bullets([
"<b>Microaneurysms</b> — earliest visible sign; small red dots from capillary wall outpouching.",
"<b>Dot-and-blot hemorrhages</b> — bleeding confined to deeper retinal layers.",
"<b>Hard exudates</b> — yellow-white lipid deposits from chronic leakage.",
"<b>Cotton wool spots</b> — pale, fluffy patches representing nerve fiber layer micro-infarcts (retinal ischemia).",
"<b>Venous beading</b> and <b>IRMA</b> (intraretinal microvascular abnormalities) — signs of worsening ischemia, seen in severe/pre-proliferative NPDR.",
]))
story.append(sub("Signs — Proliferative Diabetic Retinopathy (PDR)"))
story.append(bullets([
"<b>Neovascularization</b> at the disc (NVD) or elsewhere (NVE) — fragile new vessels growing in response to ischemia/VEGF.",
"<b>Vitreous hemorrhage</b> — from rupture of fragile new vessels.",
"<b>Fibrovascular proliferation</b> and <b>tractional retinal detachment</b> — end-stage complication.",
"<b>Laser photocoagulation scars</b> may be visible after treatment.",
]))
story.extend(fig(f"{IMG}/npdr_pdr_compare.jpg", max_width_cm=15,
caption="Fundus comparison: (A) NPDR with isolated hemorrhage and a cotton wool spot; (B) PDR with disc neovascularization, hard exudates, and macular exudation."))
story.extend(fig(f"{IMG}/dr_progression_multipanel.jpg", max_width_cm=15,
caption="Progression of diabetic retinopathy on fundus photography and OCT: microaneurysms/hemorrhages, clinically significant macular edema, cotton wool spots, venous beading, IRMA, neovascularization, pre-retinal/vitreous hemorrhage, and laser scars."))
story.append(PageBreak())
story.extend(fig(f"{IMG}/dr_fa_progression.jpg", max_width_cm=15,
caption="Fundus photographs and fluorescein angiography (FA) showing progression from moderate/severe NPDR to early and high-risk PDR, with vascular leakage and capillary non-perfusion (ischemia) on FA."))
story.append(sub("Diabetic Macular Edema (DME)"))
story.append(P("DME can occur at any stage of retinopathy and is a leading cause of vision loss in diabetics. It results from breakdown of the blood-retinal barrier causing fluid accumulation in the macula."))
story.extend(fig(f"{IMG}/dme_oct_scan.jpg", max_width_cm=13,
caption="OCT cross-section showing diabetic macular edema: retinal thickening, distorted foveal contour, and cystoid intraretinal fluid spaces."))
story.extend(fig(f"{IMG}/dme_oct_progression.jpg", max_width_cm=15,
caption="OCT series showing structural progression from a normal macula to diabetic macular edema and ischemic proliferative disease (cystic spaces, subretinal fluid, hard exudates, retinal thinning)."))
story.append(sub("Diagnosis"))
story.append(bullets([
"Dilated fundoscopic examination (annual screening for all diabetics).",
"Fundus fluorescein angiography (FA) — detects leakage, neovascularization, and capillary non-perfusion.",
"Optical coherence tomography (OCT) — quantifies macular thickness and detects fluid/cystic changes in DME.",
]))
story.append(sub("Management"))
story.append(bullets([
"Strict glycemic and blood pressure control (slows progression at every stage).",
"<b>Panretinal laser photocoagulation</b> for PDR.",
"<b>Focal/grid laser</b> or <b>anti-VEGF intravitreal injections</b> (ranibizumab, bevacizumab, aflibercept) for macular edema.",
"Vitrectomy for vitreous hemorrhage or tractional retinal detachment.",
]))
story.append(PageBreak())
story.append(sub("Other Diabetic Eye Disease (Beyond Retinopathy)"))
story.append(subsub("Diabetic Cataract"))
story.append(bullets([
"Diabetics develop cataracts earlier and more frequently than non-diabetics.",
"Mechanism: chronic hyperglycemia → increased flux through the polyol pathway → sorbitol accumulation in the lens → osmotic swelling and oxidative damage to lens fibers → opacification.",
"Presents as generalized lens haziness reducing visualization of retinal details, and blurred vision.",
]))
story.append(subsub("Diabetic Papillopathy"))
story.append(P("Mild, often self-limiting swelling of the optic disc seen in some diabetics; must be distinguished from more serious causes of disc edema."))
story.append(subsub("Neovascular Glaucoma"))
story.append(P("A severe complication of long-standing ischemic PDR: VEGF-driven new vessels grow over the iris and into the anterior chamber angle (rubeosis iridis), blocking aqueous outflow and causing a markedly elevated, difficult-to-control intraocular pressure."))
story.append(subsub("Third, Fourth, and Sixth Cranial Nerve Palsies"))
story.append(P("Diabetic mononeuropathy can cause an acute, painful third nerve palsy (classically pupil-sparing, due to ischemia of the central fascicles with sparing of peripherally located pupillary fibers), or isolated fourth/sixth nerve palsies causing diplopia."))
story.extend(fig(f"{IMG}/ocular_pathology_compare.jpg", max_width_cm=15,
caption="Comparative fundus panel: age-related macular degeneration, cataract (generalized haziness), diabetic retinopathy, glaucoma (disc cupping), hypertensive retinopathy, and a normal eye for reference."))
story.append(PageBreak())
# ============================================================
# 6. NEPHROPATHY
# ============================================================
story.append(section(6, "Diabetic Nephropathy"))
story.append(bullets([
"<b>Pathophysiology:</b> glomerular hyperfiltration (early) → mesangial matrix expansion → glomerular basement membrane thickening → <b>Kimmelstiel-Wilson nodules</b> (nodular glomerulosclerosis, pathognomonic) → progressive glomerulosclerosis.",
"<b>Stages:</b> hyperfiltration → microalbuminuria (30–300 mg/24h) → overt/macroalbuminuria (>300 mg/24h) → declining GFR → ESRD.",
"<b>Screening:</b> annual urine albumin-to-creatinine ratio (ACR) and eGFR, starting at diagnosis (T2DM) or 5 years post-diagnosis (T1DM).",
"<b>Management:</b> strict glycemic control, BP control (target <130/80), ACE inhibitors/ARBs (reduce intraglomerular pressure), SGLT2 inhibitors (proven renal protective effect independent of glycemic control), protein restriction in advanced CKD.",
]))
story.append(PageBreak())
# ============================================================
# 7. DIABETIC FOOT
# ============================================================
story.append(section(7, "Diabetic Foot"))
story.append(bullets([
"<b>Pathophysiology:</b> triad of (1) peripheral neuropathy (sensory loss = loss of protective sensation, motor neuropathy = foot deformity, autonomic neuropathy = dry skin/reduced sweating), (2) peripheral arterial disease (macrovascular ischemia), (3) immunopathy (impaired leukocyte function → susceptibility to infection).",
"<b>Clinical features:</b> painless ulcers (typically over pressure points — metatarsal heads, heel), callus formation, <b>Charcot foot</b> (neuropathic joint destruction, rocker-bottom deformity), gangrene.",
"<b>Classification:</b> Wagner classification (grade 0–5, based on depth/tissue loss/gangrene) or University of Texas classification (grade + stage for infection/ischemia).",
"<b>Diagnosis:</b> 10g Semmes-Weinstein monofilament testing, vibration perception (biothesiometer), ankle-brachial index (ABI) for arterial disease, probe-to-bone test for osteomyelitis, imaging (X-ray/MRI).",
"<b>Management:</b> regular foot inspection, offloading devices, wound debridement, infection control (antibiotics), revascularization if ischemic, patient education, appropriate footwear.",
]))
story.append(PageBreak())
# ============================================================
# 8. CARDIAC
# ============================================================
story.append(section(8, "Cardiac Associations of Diabetes Mellitus"))
story.append(bullets([
"<b>Accelerated atherosclerosis:</b> hyperglycemia, dyslipidemia, and insulin resistance promote endothelial dysfunction, advanced glycation end-products (AGEs), and inflammation → accelerated coronary artery disease.",
"<b>Diabetic cardiomyopathy:</b> myocardial dysfunction independent of coronary disease/hypertension, driven by lipotoxicity, myocardial fibrosis, mitochondrial dysfunction, and AGE cross-linking — manifests as diastolic dysfunction progressing to heart failure.",
"<b>Silent myocardial ischemia:</b> autonomic neuropathy blunts anginal pain perception → higher risk of unrecognized MI.",
"<b>Autonomic neuropathy:</b> resting tachycardia, orthostatic hypotension, reduced heart rate variability.",
"<b>Heart failure:</b> diabetics have 2–4x increased risk of heart failure (both HFrEF and HFpEF).",
"<b>Management:</b> aggressive risk factor control (statins, BP control), SGLT2 inhibitors (proven cardiovascular/heart failure benefit), GLP-1 receptor agonists (proven MACE reduction), antiplatelet therapy where indicated.",
]))
story.append(PageBreak())
# ============================================================
# 9. NAFLD - DETAILED
# ============================================================
story.append(section(9, "Non-Alcoholic Fatty Liver Disease (NAFLD) — Detailed"))
story.append(sub("Definition and Epidemiology"))
story.append(P("NAFLD is defined as hepatic steatosis (fat in >5% of hepatocytes) on imaging or biopsy in the absence of significant alcohol use or other secondary causes of fat accumulation. It is now the most common chronic liver disease worldwide and is present in up to 55-70% of people with type 2 diabetes, reflecting the shared driver of insulin resistance."))
story.append(sub("Pathophysiology"))
story.append(subsub("The 'Multiple-Hit' Model"))
story.append(bullets([
"<b>Insulin resistance</b> is central: it impairs suppression of adipose tissue lipolysis → increased free fatty acid (FFA) flux to the liver.",
"Hyperinsulinemia also directly stimulates hepatic <b>de novo lipogenesis</b> via SREBP-1c activation, and impairs fatty acid oxidation.",
"Excess FFAs accumulate as hepatic triglyceride (simple steatosis) — the 'first hit'.",
"<b>Lipotoxicity:</b> toxic lipid intermediates (diacylglycerol, ceramides, free cholesterol - not triglyceride itself) cause mitochondrial dysfunction, ER stress, and oxidative stress ('second hit').",
"This drives hepatocyte injury (ballooning), activation of Kupffer cells and hepatic stellate cells, and an inflammatory/fibrogenic response → progression from simple fatty liver to <b>steatohepatitis (NASH)</b>.",
"Gut-derived factors (dysbiosis, increased intestinal permeability/endotoxin) and genetic polymorphisms (e.g., PNPLA3, TM6SF2) modulate individual risk and rate of progression.",
]))
story.append(sub("Spectrum / Stages of Disease"))
story.append(make_table(
["Stage", "Features"],
[
["NAFL (simple steatosis)", "Hepatic fat accumulation without significant inflammation or hepatocyte injury; generally benign, slow progression"],
["NASH (non-alcoholic steatohepatitis)", "Steatosis + lobular inflammation + hepatocyte ballooning injury +/- Mallory-Denk bodies; can progress to fibrosis"],
["Fibrosis (F1-F4)", "Progressive peri-sinusoidal/portal fibrosis from NASH; F4 = cirrhosis"],
["Cirrhosis", "End-stage fibrosis with architectural distortion; risk of decompensation and portal hypertension"],
["Hepatocellular carcinoma (HCC)", "Can arise from NASH-cirrhosis, and occasionally from NASH without cirrhosis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(sub("Risk Factors"))
story.append(bullets([
"Type 2 diabetes mellitus and insulin resistance (strongest associations).",
"Obesity, especially visceral/central adiposity.",
"Metabolic syndrome (dyslipidemia - especially high triglycerides/low HDL, hypertension).",
"Polycystic ovary syndrome, hypothyroidism, obstructive sleep apnea (associated conditions).",
]))
story.append(sub("Clinical Features"))
story.append(bullets([
"Usually asymptomatic; may have vague right upper quadrant discomfort or fatigue.",
"Hepatomegaly may be present on examination.",
"Signs of cirrhosis (spider angiomata, palmar erythema, ascites, jaundice) only in advanced disease.",
]))
story.append(sub("Diagnosis"))
story.append(bullets([
"<b>Liver enzymes:</b> mild elevation of ALT and AST, typically ALT > AST (reverses toward AST-predominant as fibrosis/cirrhosis develops); enzymes can also be entirely normal.",
"<b>Imaging:</b> ultrasound (hyperechoic 'bright liver', first-line, but insensitive for mild steatosis); CT/MRI more sensitive; <b>MRI-PDFF</b> is the most accurate non-invasive quantifier of fat.",
"<b>Non-invasive fibrosis scores:</b> FIB-4 index and NAFLD Fibrosis Score (NFS) using age, BMI, platelets, albumin, AST/ALT — used to risk-stratify and decide who needs specialist referral or biopsy.",
"<b>Transient elastography (FibroScan)</b> and MR elastography — assess liver stiffness as a surrogate for fibrosis.",
"<b>Liver biopsy</b> — gold standard; required to definitively diagnose NASH and stage fibrosis, but invasive; reserved for diagnostic uncertainty or when it will change management.",
]))
story.append(sub("Management"))
story.append(bullets([
"<b>Weight loss</b> — the cornerstone of treatment; 7-10% body weight loss improves steatosis, inflammation, and can regress fibrosis; >10% loss shown to induce NASH resolution in many patients.",
"<b>Glycemic control</b> — optimize diabetes management; poor glycemic control accelerates progression.",
"<b>Pioglitazone</b> — improves hepatic histology (steatosis and inflammation) in biopsy-proven NASH, including in diabetics; weight gain and fluid retention are trade-offs.",
"<b>GLP-1 receptor agonists</b> (liraglutide, semaglutide) — promote weight loss and have shown histological improvement in NASH trials.",
"<b>Vitamin E</b> — may be used in non-diabetic biopsy-proven NASH (antioxidant effect); use is more controversial in diabetics.",
"Avoid alcohol; manage dyslipidemia (statins are safe in NAFLD/NASH and do not need to be withheld); bariatric surgery can be considered in eligible obese patients and improves/resolves NASH in many.",
"Screen for and manage cardiovascular risk — cardiovascular disease, not liver disease, is the leading cause of death in NAFLD patients.",
"Surveillance for hepatocellular carcinoma and varices once cirrhosis develops.",
]))
story.append(PageBreak())
# ============================================================
# 10. IDM - RESTRUCTURED (Mother + Fetus + Baby)
# ============================================================
story.append(section(10, "Infant of a Diabetic Mother (IDM)"))
story.append(sub("Pathophysiology — The Pedersen Hypothesis"))
story.append(P("Maternal hyperglycemia crosses the placenta freely (glucose crosses; maternal insulin does not). This exposes the fetus to chronically elevated glucose → fetal pancreatic beta-cell hyperplasia → <b>fetal hyperinsulinemia</b>. Because insulin is a potent fetal growth factor, this single mechanism (fetal hyperinsulinemia) underlies almost all classic complications of IDM — both during pregnancy and after birth."))
story.append(sub("A. Complications to the Mother (during pregnancy)"))
story.append(bullets([
"<b>Pre-eclampsia / gestational hypertension</b> — 2-4x more common in diabetic pregnancies, especially with pre-existing vascular disease.",
"<b>Polyhydramnios</b> — fetal hyperglycemia causes fetal polyuria, increasing amniotic fluid volume; raises risk of preterm labor and malpresentation.",
"<b>Worsening of maternal diabetic retinopathy and nephropathy</b> — pregnancy can accelerate progression of existing microvascular disease.",
"<b>Diabetic ketoacidosis (DKA)</b> — pregnancy is a ketogenic state; DKA can occur at lower glucose thresholds than in non-pregnant patients and is dangerous for both mother and fetus.",
"<b>Increased infection risk</b> — urinary tract infections, candidiasis.",
"<b>Obstructed/prolonged labor and operative delivery</b> — due to fetal macrosomia; increased rates of Cesarean section.",
"<b>Postpartum hemorrhage</b> — from uterine overdistension (polyhydramnios/macrosomia) and prolonged labor.",
]))
story.append(sub("B. Complications to the Fetus (during pregnancy / at birth)"))
story.append(bullets([
"<b>Macrosomia</b> (birth weight >4 kg or >90th percentile) — fetal hyperinsulinemia drives excess growth of insulin-sensitive tissues (fat, muscle, organomegaly), sparing the brain — classic asymmetric growth with increased shoulder/trunk size predisposing to <b>shoulder dystocia</b> and birth trauma (brachial plexus injury, clavicle fracture).",
"<b>Congenital malformations</b> (2-4x general population risk) — related to poor glycemic control during organogenesis (first trimester, weeks 3-8): cardiac defects (VSD, transposition of the great vessels), neural tube defects, and the classic but rare <b>caudal regression syndrome (sacral agenesis)</b>.",
"<b>Intrauterine growth restriction (IUGR)</b> — can occur instead of macrosomia if the mother has advanced vascular disease (placental insufficiency).",
"<b>Unexplained stillbirth</b> — risk increased with poor glycemic control, especially in the third trimester.",
"<b>Fetal hypoxia</b> — chronic hyperglycemia increases fetal oxygen consumption and can cause relative intrauterine hypoxia, stimulating erythropoietin and polycythemia.",
]))
story.append(sub("C. Treatment / Management of the Mother During Pregnancy"))
story.append(bullets([
"<b>Preconception counseling</b> — optimize HbA1c (target <6.5% ideally) before conception to reduce malformation risk; start high-dose folic acid.",
"<b>Glycemic targets in pregnancy</b> — tighter than usual: fasting <95 mg/dL, 1-hr postprandial <140 mg/dL, 2-hr postprandial <120 mg/dL.",
"<b>Insulin is the preferred pharmacologic agent in pregnancy</b> (does not cross the placenta in clinically significant amounts); doses typically need to increase progressively through pregnancy due to rising insulin resistance from placental hormones (human placental lactogen, cortisol, progesterone).",
"Metformin and glyburide are sometimes used (particularly in gestational diabetes) but insulin remains first-line/preferred, especially in pre-existing diabetes.",
"<b>Self-monitoring of blood glucose</b> multiple times daily; regular HbA1c monitoring.",
"<b>Ophthalmologic exam</b> each trimester (risk of retinopathy progression); renal function monitoring.",
"<b>Nutrition/dietary counseling</b> and regular physical activity as tolerated.",
"Low-dose aspirin from the end of the first trimester to reduce pre-eclampsia risk (standard for pregestational diabetes).",
]))
story.append(sub("D. Monitoring / Treatment of the Fetus During Pregnancy"))
story.append(bullets([
"<b>Serial growth ultrasounds</b> — monitor for macrosomia or growth restriction, and amniotic fluid volume (polyhydramnios).",
"<b>Fetal echocardiography</b> — offered given increased risk of congenital heart defects.",
"<b>Antenatal fetal surveillance</b> in the third trimester — non-stress tests (NST), biophysical profile, umbilical artery Doppler if growth-restricted.",
"<b>Timing of delivery</b> — individualized; often delivery is planned around 39-40 weeks (earlier if poor control, macrosomia, or other complications) to balance risks of stillbirth against prematurity.",
"Consideration of elective Cesarean section if estimated fetal weight is very high, to reduce shoulder dystocia risk.",
]))
story.append(sub("E. Management of the Baby After Birth (Neonatal Period)"))
story.append(bullets([
"<b>Neonatal hypoglycemia</b> — the most important immediate risk: after cord clamping, the maternal glucose supply stops abruptly but fetal hyperinsulinemia persists for hours to days → profound hypoglycemia. Manage with early feeding within the first hour, frequent bedside glucose monitoring (per protocol, e.g., at 30 min, 1, 2, 4, 6, 12, 24 hours), and IV dextrose if symptomatic or glucose remains low despite feeding.",
"<b>Respiratory distress syndrome (RDS)</b> — fetal hyperinsulinemia antagonizes cortisol's stimulation of surfactant production, delaying lung maturity even at term; monitor respiratory status closely and support as needed (may require surfactant/NICU care).",
"<b>Hypertrophic cardiomyopathy</b> — transient septal/ventricular wall thickening from hyperinsulinemia; usually resolves over weeks to months; echocardiogram if murmur or respiratory/feeding difficulty.",
"<b>Polycythemia</b> — from chronic relative intrauterine hypoxia driving erythropoietin; monitor hematocrit; partial exchange transfusion rarely needed for severe symptomatic cases.",
"<b>Hyperbilirubinemia/jaundice</b> — from breakdown of excess red cells (polycythemia) and immature hepatic conjugation; monitor bilirubin, treat with phototherapy as needed.",
"<b>Hypocalcemia and hypomagnesemia</b> — due to delayed parathyroid hormone response; monitor calcium/magnesium, supplement if symptomatic (jitteriness, seizures).",
"<b>Birth injury</b> from macrosomia/shoulder dystocia — examine for brachial plexus injury (Erb's palsy), clavicle fracture, cephalohematoma.",
"<b>Screen for congenital anomalies</b> if not already characterized antenatally (cardiac exam/echo, spine exam).",
"Longer-term: IDM babies have increased lifetime risk of obesity, impaired glucose tolerance, and type 2 diabetes themselves — anticipatory guidance for the family."
]))
story.append(Spacer(1, 20))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#B0B0B0")))
story.append(Spacer(1, 6))
story.append(Paragraph(
"<i>This study guide is compiled from standard medical education content for exam preparation purposes. "
"Always verify current clinical guidelines and drug dosing against up-to-date primary sources before clinical application.</i>",
styles["Body"]
))
def add_page_number(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.setFillColor(colors.grey)
canvas.drawCentredString(A4[0] / 2, 1.2 * cm, f"Page {doc.page} | Diabetes Mellitus Study Guide")
canvas.restoreState()
doc = SimpleDocTemplate(
OUT, pagesize=A4,
topMargin=1.8*cm, bottomMargin=1.8*cm, leftMargin=1.8*cm, rightMargin=1.8*cm,
title="Diabetes Mellitus Study Guide"
)
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
print("PDF written to", OUT)
rm -f /tmp/workspace/diabetes-study-guide/build_pdf.py
~/diabetes-study-guide/build_pdf.py
#!/usr/bin/env python3
"""Build the Diabetes Mellitus Study Guide PDF - v2 (flowcharts, eye images, expanded NAFLD & IDM)."""
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
PageBreak, ListFlowable, ListItem, HRFlowable, Image
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from PIL import Image as PILImage
BASE = "/tmp/workspace/diabetes-study-guide"
IMG = f"{BASE}/images"
OUT = f"{BASE}/Diabetes_Mellitus_Study_Guide.pdf"
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="TitleBig", fontSize=24, leading=28, alignment=TA_CENTER,
textColor=colors.HexColor("#1a3d5c"), spaceAfter=6, fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Subtitle", fontSize=13, leading=16, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), spaceAfter=20, fontName="Helvetica"))
styles.add(ParagraphStyle(name="SectionHeading", fontSize=16, leading=20, spaceBefore=14, spaceAfter=8,
textColor=colors.white, backColor=colors.HexColor("#1a3d5c"),
fontName="Helvetica-Bold", leftIndent=6, borderPadding=6))
styles.add(ParagraphStyle(name="SubHeading", fontSize=12.5, leading=15, spaceBefore=10, spaceAfter=4,
textColor=colors.HexColor("#1a3d5c"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="SubSubHeading", fontSize=11, leading=13, spaceBefore=8, spaceAfter=3,
textColor=colors.HexColor("#c0622a"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Body", fontSize=10, leading=14, spaceAfter=4, alignment=TA_LEFT, fontName="Helvetica"))
styles.add(ParagraphStyle(name="BulletBody", fontSize=10, leading=13.5, spaceAfter=2, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TOCItem", fontSize=11, leading=18, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableCell", fontSize=8.7, leading=11, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableHeader", fontSize=9, leading=11, fontName="Helvetica-Bold", textColor=colors.white))
styles.add(ParagraphStyle(name="Caption", fontSize=8.5, leading=10.5, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), fontName="Helvetica-Oblique", spaceAfter=10))
def P(text):
return Paragraph(text, styles["Body"])
def bullets(items):
return ListFlowable(
[ListItem(Paragraph(i, styles["BulletBody"]), leftIndent=6) for i in items],
bulletType="bullet", start="•", leftIndent=14, spaceBefore=2, spaceAfter=6
)
def make_table(header, rows, col_widths=None):
data = [[Paragraph(h, styles["TableHeader"]) for h in header]]
for r in rows:
data.append([Paragraph(str(c), styles["TableCell"]) for c in r])
t = Table(data, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1a3d5c")),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#B0B0B0")),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#EEF3F7")]),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]))
return t
def section(num, title):
return Paragraph(f"{num}. {title}", styles["SectionHeading"])
def sub(title):
return Paragraph(title, styles["SubHeading"])
def subsub(title):
return Paragraph(title, styles["SubSubHeading"])
def fig(path, max_width_cm=16.5, caption=None):
im = PILImage.open(path)
w, h = im.size
max_w = max_width_cm * cm
scale = max_w / w
max_h = 21 * cm # safety cap
disp_w = max_w
disp_h = h * scale
if disp_h > max_h:
disp_h = max_h
disp_w = w * (max_h / h)
flow = [Image(path, width=disp_w, height=disp_h)]
if caption:
flow.append(Paragraph(caption, styles["Caption"]))
return flow
story = []
# ---------- Cover ----------
story.append(Spacer(1, 3.2 * cm))
story.append(Paragraph("Diabetes Mellitus", styles["TitleBig"]))
story.append(Paragraph("Complete Study Guide", styles["TitleBig"]))
story.append(Paragraph("Biochemistry · Diagnosis · Pharmacology · Complications · Special Populations", styles["Subtitle"]))
story.append(Spacer(1, 1*cm))
story.append(HRFlowable(width="80%", thickness=1, color=colors.HexColor("#1a3d5c"), hAlign="CENTER"))
story.append(Spacer(1, 1*cm))
toc_items = [
"1. Biochemistry of Insulin Formation and Glucose Metabolism (with flowcharts)",
"2. Diagnosis of Diabetes Mellitus — Tests, Markers, Values",
"3. Pharmacological Drugs — Classification and Receptors",
"4. Types of Insulin Supplements",
"5. Diabetic Retinopathy and Other Diabetic Eye Disease (with images)",
"6. Diabetic Nephropathy",
"7. Diabetic Foot",
"8. Cardiac Associations of Diabetes Mellitus",
"9. Non-Alcoholic Fatty Liver Disease (NAFLD) — Detailed",
"10. Infant of a Diabetic Mother (IDM) — Maternal & Fetal Complications and Management",
]
story.append(Paragraph("Contents (Correct Study Order)", styles["SubHeading"]))
for item in toc_items:
story.append(Paragraph(item, styles["TOCItem"]))
story.append(PageBreak())
# ============================================================
# 1. BIOCHEMISTRY (with flowcharts)
# ============================================================
story.append(section(1, "Biochemistry of Insulin Formation and Glucose Metabolism"))
story.append(sub("Insulin Synthesis"))
story.append(bullets([
"Insulin gene (chromosome 11) transcribed in pancreatic beta cells → mRNA translated into <b>preproinsulin</b> on rough ER ribosomes.",
"Signal peptide cleaved → <b>proinsulin</b> (single chain: A-chain, B-chain, connecting C-peptide, held by 2 disulfide bonds).",
"Proinsulin transported to Golgi, packaged into secretory granules, cleaved by prohormone convertases (PC1/3, PC2) and carboxypeptidase E → <b>insulin (A+B chains linked by disulfide bonds) + C-peptide</b> in equimolar amounts.",
"C-peptide has no known metabolic activity but is a useful clinical marker of endogenous insulin production (unaffected by exogenous insulin injections).",
]))
story.extend(fig(f"{IMG}/flowchart_insulin_formation.png", max_width_cm=11,
caption="Flowchart 1: Insulin biosynthesis pathway from gene transcription to mature hormone."))
story.append(sub("Insulin Secretion Mechanism (Beta Cell)"))
story.append(bullets([
"Glucose enters the beta cell via the <b>GLUT2</b> transporter.",
"Glucokinase phosphorylates glucose (rate-limiting "glucose sensor" step).",
"Glycolysis/oxidative metabolism raises the ATP:ADP ratio.",
"ATP closes <b>ATP-sensitive K+ channels (K<sub>ATP</sub>: SUR1/Kir6.2 subunits)</b> → membrane depolarization.",
"Voltage-gated Ca2+ channels open → Ca2+ influx → triggers exocytosis of insulin granules.",
"Biphasic release: first phase (stored granules, rapid) and second phase (newly synthesized insulin, sustained).",
]))
story.append(PageBreak())
story.extend(fig(f"{IMG}/flowchart_insulin_secretion.png", max_width_cm=11,
caption="Flowchart 2: Glucose-stimulated insulin secretion pathway in the pancreatic beta cell."))
story.append(sub("Insulin Receptor and Signaling"))
story.append(bullets([
"Insulin receptor: tetrameric transmembrane <b>receptor tyrosine kinase</b> (2 alpha + 2 beta subunits).",
"Insulin binding → autophosphorylation of beta subunits → phosphorylates <b>IRS-1/IRS-2</b> → activates <b>PI3K/Akt pathway</b> → triggers <b>GLUT4 translocation</b> to the cell membrane in muscle/adipose tissue → glucose uptake.",
"A parallel <b>Ras/MAPK pathway</b> mediates insulin's growth/mitogenic effects.",
]))
story.append(PageBreak())
story.extend(fig(f"{IMG}/flowchart_insulin_signaling.png", max_width_cm=15,
caption="Flowchart 3: Insulin receptor signal transduction and downstream effects on glucose, glycogen, and lipid metabolism."))
story.append(sub("Glucose Metabolism — Insulin's Actions (Summary Table)"))
story.append(make_table(
["Pathway", "Effect of Insulin"],
[
["Glycolysis", "Stimulates (hexokinase, PFK-1, pyruvate kinase induction)"],
["Glycogenesis", "Stimulates (activates glycogen synthase)"],
["Glycogenolysis", "Inhibits"],
["Gluconeogenesis", "Inhibits (suppresses PEPCK, fructose-1,6-bisphosphatase, glucose-6-phosphatase)"],
["Lipogenesis", "Stimulates (activates acetyl-CoA carboxylase, fatty acid synthase)"],
["Lipolysis", "Inhibits (inhibits hormone-sensitive lipase)"],
["Proteolysis", "Inhibits; promotes protein synthesis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(Spacer(1, 6))
story.append(P("<b>Counter-regulatory hormones:</b> glucagon (stimulates glycogenolysis/gluconeogenesis via cAMP/PKA), epinephrine, cortisol, growth hormone — all raise blood glucose, opposing insulin."))
story.append(PageBreak())
# ============================================================
# 2. DIAGNOSIS
# ============================================================
story.append(section(2, "Diagnosis of Diabetes Mellitus — Tests, Markers, Values"))
story.append(P("Diagnostic criteria (ADA/WHO) — any one confirmed on two occasions (unless unequivocal hyperglycemia with symptoms):"))
story.append(make_table(
["Test", "Normal", "Prediabetes", "Diabetes"],
[
["Fasting Plasma Glucose (FPG)", "<100 mg/dL (5.6 mmol/L)", "100–125 mg/dL", "≥126 mg/dL (7.0 mmol/L)"],
["2-hr OGTT (75g glucose load)", "<140 mg/dL", "140–199 mg/dL", "≥200 mg/dL (11.1 mmol/L)"],
["HbA1c", "<5.7%", "5.7–6.4%", "≥6.5%"],
["Random Plasma Glucose + symptoms", "-", "-", "≥200 mg/dL"],
],
col_widths=[6*cm, 3.5*cm, 3.5*cm, 3.5*cm]
))
story.append(Spacer(1, 8))
story.append(sub("Gestational Diabetes Screening"))
story.append(P("24–28 weeks gestation, 75g OGTT (one-step): fasting ≥92, 1-hr ≥180, 2-hr ≥153 mg/dL (any one abnormal = GDM); or two-step approach with 50g screen followed by 100g OGTT."))
story.append(sub("Classification Markers"))
story.append(bullets([
"<b>Type 1 DM:</b> autoantibodies — GAD65, islet cell antibodies (ICA), IA-2 (insulinoma-associated antigen 2), insulin autoantibodies (IAA), ZnT8 antibodies. Low/absent C-peptide.",
"<b>Type 2 DM:</b> normal/high C-peptide (insulin resistance), no autoantibodies, associated with obesity/metabolic syndrome.",
"<b>MODY:</b> genetic (e.g., HNF1A, GCK mutations), autosomal dominant, young onset without autoimmunity.",
]))
story.append(sub("Other Markers"))
story.append(bullets([
"Urine glucose (glucosuria — renal threshold ~180 mg/dL).",
"Urine/serum ketones — diabetic ketoacidosis (Type 1).",
"Microalbuminuria (30–300 mg/24h) — early nephropathy marker.",
"C-peptide — differentiates endogenous vs exogenous insulin, assesses beta cell reserve.",
]))
story.append(PageBreak())
# ============================================================
# 3. PHARMACOLOGY
# ============================================================
story.append(section(3, "Pharmacological Drugs — Classification and Receptors"))
story.append(make_table(
["Class", "Examples", "Mechanism / Receptor Target", "Key Side Effects"],
[
["Biguanides", "Metformin", "Activates AMPK; decreases hepatic gluconeogenesis, increases peripheral insulin sensitivity", "GI upset, lactic acidosis (rare), B12 deficiency"],
["Sulfonylureas", "Glibenclamide, Glipizide, Glimepiride", "Bind SUR1 subunit of K_ATP channel on beta cells → closes channel → insulin release", "Hypoglycemia, weight gain"],
["Meglitinides", "Repaglinide, Nateglinide", "Same K_ATP/SUR1 site, faster/shorter action", "Hypoglycemia (less than SU)"],
["Thiazolidinediones (TZDs)", "Pioglitazone, Rosiglitazone", "Activate PPAR-gamma nuclear receptor → improves insulin sensitivity in adipose/muscle", "Weight gain, fluid retention, heart failure risk, fracture risk"],
["Alpha-glucosidase inhibitors", "Acarbose, Miglitol", "Inhibit intestinal alpha-glucosidase → delay carbohydrate absorption", "Flatulence, GI upset"],
["DPP-4 inhibitors (gliptins)", "Sitagliptin, Vildagliptin, Linagliptin", "Inhibit dipeptidyl peptidase-4 → increases endogenous GLP-1/GIP levels", "Generally well tolerated; pancreatitis risk (rare)"],
["GLP-1 receptor agonists", "Exenatide, Liraglutide, Semaglutide, Dulaglutide", "Agonists at GLP-1 receptor → glucose-dependent insulin secretion, decreases glucagon, delays gastric emptying, satiety", "Nausea, vomiting, pancreatitis risk"],
["SGLT2 inhibitors", "Empagliflozin, Dapagliflozin, Canagliflozin", "Inhibit sodium-glucose cotransporter 2 in proximal renal tubule → glucosuria", "UTI, genital mycotic infections, euglycemic DKA"],
["Amylin analogs", "Pramlintide", "Mimics amylin, co-secreted with insulin — slows gastric emptying, suppresses glucagon", "Nausea, hypoglycemia (with insulin)"],
["Insulin", "See Section 4", "Insulin receptor (tyrosine kinase)", "Hypoglycemia, weight gain"],
],
col_widths=[3.4*cm, 3.6*cm, 6.8*cm, 2.7*cm]
))
story.append(PageBreak())
# ============================================================
# 4. INSULIN TYPES
# ============================================================
story.append(section(4, "Types of Insulin Supplements"))
story.append(make_table(
["Type", "Examples", "Onset", "Peak", "Duration"],
[
["Rapid-acting", "Lispro, Aspart, Glulisine", "10–15 min", "1–2 hr", "3–5 hr"],
["Short-acting (Regular)", "Regular human insulin", "30–60 min", "2–3 hr", "5–8 hr"],
["Intermediate-acting", "NPH (isophane)", "2–4 hr", "4–10 hr", "10–16 hr"],
["Long-acting", "Glargine, Detemir", "1–2 hr", "minimal peak", "20–24 hr"],
["Ultra-long-acting", "Degludec", "30–90 min", "minimal peak", "up to 42 hr"],
["Premixed", "70/30 NPH/Regular, 75/25 lispro protamine/lispro", "Combination profile", "Combination", "Combination"],
],
col_widths=[3.7*cm, 5.8*cm, 2.6*cm, 2.6*cm, 2.6*cm]
))
story.append(Spacer(1, 8))
story.append(P("<b>Clinical use:</b> rapid-acting insulin is used for prandial control (given with meals); long-acting/basal insulin provides background coverage; premixed formulations offer simplified regimens for select patients."))
story.append(PageBreak())
# ============================================================
# 5. RETINOPATHY + OTHER EYE DISEASE (with images)
# ============================================================
story.append(section(5, "Diabetic Retinopathy and Other Diabetic Eye Disease"))
story.append(sub("Pathophysiology"))
story.append(P("Chronic hyperglycemia causes pericyte loss, thickening of the retinal capillary basement membrane, and microvascular occlusion. The resulting retinal ischemia raises VEGF (vascular endothelial growth factor), which drives leakage and, later, abnormal new vessel growth."))
story.append(sub("Signs — Non-Proliferative Diabetic Retinopathy (NPDR)"))
story.append(bullets([
"<b>Microaneurysms</b> — earliest visible sign; small red dots from capillary wall outpouching.",
"<b>Dot-and-blot hemorrhages</b> — bleeding confined to deeper retinal layers.",
"<b>Hard exudates</b> — yellow-white lipid deposits from chronic leakage.",
"<b>Cotton wool spots</b> — pale, fluffy patches representing nerve fiber layer micro-infarcts (retinal ischemia).",
"<b>Venous beading</b> and <b>IRMA</b> (intraretinal microvascular abnormalities) — signs of worsening ischemia, seen in severe/pre-proliferative NPDR.",
]))
story.append(sub("Signs — Proliferative Diabetic Retinopathy (PDR)"))
story.append(bullets([
"<b>Neovascularization</b> at the disc (NVD) or elsewhere (NVE) — fragile new vessels growing in response to ischemia/VEGF.",
"<b>Vitreous hemorrhage</b> — from rupture of fragile new vessels.",
"<b>Fibrovascular proliferation</b> and <b>tractional retinal detachment</b> — end-stage complication.",
"<b>Laser photocoagulation scars</b> may be visible after treatment.",
]))
story.extend(fig(f"{IMG}/npdr_pdr_compare.jpg", max_width_cm=15,
caption="Fundus comparison: (A) NPDR with isolated hemorrhage and a cotton wool spot; (B) PDR with disc neovascularization, hard exudates, and macular exudation."))
story.extend(fig(f"{IMG}/dr_progression_multipanel.jpg", max_width_cm=15,
caption="Progression of diabetic retinopathy on fundus photography and OCT: microaneurysms/hemorrhages, clinically significant macular edema, cotton wool spots, venous beading, IRMA, neovascularization, pre-retinal/vitreous hemorrhage, and laser scars."))
story.append(PageBreak())
story.extend(fig(f"{IMG}/dr_fa_progression.jpg", max_width_cm=15,
caption="Fundus photographs and fluorescein angiography (FA) showing progression from moderate/severe NPDR to early and high-risk PDR, with vascular leakage and capillary non-perfusion (ischemia) on FA."))
story.append(sub("Diabetic Macular Edema (DME)"))
story.append(P("DME can occur at any stage of retinopathy and is a leading cause of vision loss in diabetics. It results from breakdown of the blood-retinal barrier causing fluid accumulation in the macula."))
story.extend(fig(f"{IMG}/dme_oct_scan.jpg", max_width_cm=13,
caption="OCT cross-section showing diabetic macular edema: retinal thickening, distorted foveal contour, and cystoid intraretinal fluid spaces."))
story.extend(fig(f"{IMG}/dme_oct_progression.jpg", max_width_cm=15,
caption="OCT series showing structural progression from a normal macula to diabetic macular edema and ischemic proliferative disease (cystic spaces, subretinal fluid, hard exudates, retinal thinning)."))
story.append(sub("Diagnosis"))
story.append(bullets([
"Dilated fundoscopic examination (annual screening for all diabetics).",
"Fundus fluorescein angiography (FA) — detects leakage, neovascularization, and capillary non-perfusion.",
"Optical coherence tomography (OCT) — quantifies macular thickness and detects fluid/cystic changes in DME.",
]))
story.append(sub("Management"))
story.append(bullets([
"Strict glycemic and blood pressure control (slows progression at every stage).",
"<b>Panretinal laser photocoagulation</b> for PDR.",
"<b>Focal/grid laser</b> or <b>anti-VEGF intravitreal injections</b> (ranibizumab, bevacizumab, aflibercept) for macular edema.",
"Vitrectomy for vitreous hemorrhage or tractional retinal detachment.",
]))
story.append(PageBreak())
story.append(sub("Other Diabetic Eye Disease (Beyond Retinopathy)"))
story.append(subsub("Diabetic Cataract"))
story.append(bullets([
"Diabetics develop cataracts earlier and more frequently than non-diabetics.",
"Mechanism: chronic hyperglycemia → increased flux through the polyol pathway → sorbitol accumulation in the lens → osmotic swelling and oxidative damage to lens fibers → opacification.",
"Presents as generalized lens haziness reducing visualization of retinal details, and blurred vision.",
]))
story.append(subsub("Diabetic Papillopathy"))
story.append(P("Mild, often self-limiting swelling of the optic disc seen in some diabetics; must be distinguished from more serious causes of disc edema."))
story.append(subsub("Neovascular Glaucoma"))
story.append(P("A severe complication of long-standing ischemic PDR: VEGF-driven new vessels grow over the iris and into the anterior chamber angle (rubeosis iridis), blocking aqueous outflow and causing a markedly elevated, difficult-to-control intraocular pressure."))
story.append(subsub("Third, Fourth, and Sixth Cranial Nerve Palsies"))
story.append(P("Diabetic mononeuropathy can cause an acute, painful third nerve palsy (classically pupil-sparing, due to ischemia of the central fascicles with sparing of peripherally located pupillary fibers), or isolated fourth/sixth nerve palsies causing diplopia."))
story.extend(fig(f"{IMG}/ocular_pathology_compare.jpg", max_width_cm=15,
caption="Comparative fundus panel: age-related macular degeneration, cataract (generalized haziness), diabetic retinopathy, glaucoma (disc cupping), hypertensive retinopathy, and a normal eye for reference."))
story.append(PageBreak())
# ============================================================
# 6. NEPHROPATHY
# ============================================================
story.append(section(6, "Diabetic Nephropathy"))
story.append(bullets([
"<b>Pathophysiology:</b> glomerular hyperfiltration (early) → mesangial matrix expansion → glomerular basement membrane thickening → <b>Kimmelstiel-Wilson nodules</b> (nodular glomerulosclerosis, pathognomonic) → progressive glomerulosclerosis.",
"<b>Stages:</b> hyperfiltration → microalbuminuria (30–300 mg/24h) → overt/macroalbuminuria (>300 mg/24h) → declining GFR → ESRD.",
"<b>Screening:</b> annual urine albumin-to-creatinine ratio (ACR) and eGFR, starting at diagnosis (T2DM) or 5 years post-diagnosis (T1DM).",
"<b>Management:</b> strict glycemic control, BP control (target <130/80), ACE inhibitors/ARBs (reduce intraglomerular pressure), SGLT2 inhibitors (proven renal protective effect independent of glycemic control), protein restriction in advanced CKD.",
]))
story.append(PageBreak())
# ============================================================
# 7. DIABETIC FOOT
# ============================================================
story.append(section(7, "Diabetic Foot"))
story.append(bullets([
"<b>Pathophysiology:</b> triad of (1) peripheral neuropathy (sensory loss = loss of protective sensation, motor neuropathy = foot deformity, autonomic neuropathy = dry skin/reduced sweating), (2) peripheral arterial disease (macrovascular ischemia), (3) immunopathy (impaired leukocyte function → susceptibility to infection).",
"<b>Clinical features:</b> painless ulcers (typically over pressure points — metatarsal heads, heel), callus formation, <b>Charcot foot</b> (neuropathic joint destruction, rocker-bottom deformity), gangrene.",
"<b>Classification:</b> Wagner classification (grade 0–5, based on depth/tissue loss/gangrene) or University of Texas classification (grade + stage for infection/ischemia).",
"<b>Diagnosis:</b> 10g Semmes-Weinstein monofilament testing, vibration perception (biothesiometer), ankle-brachial index (ABI) for arterial disease, probe-to-bone test for osteomyelitis, imaging (X-ray/MRI).",
"<b>Management:</b> regular foot inspection, offloading devices, wound debridement, infection control (antibiotics), revascularization if ischemic, patient education, appropriate footwear.",
]))
story.append(PageBreak())
# ============================================================
# 8. CARDIAC
# ============================================================
story.append(section(8, "Cardiac Associations of Diabetes Mellitus"))
story.append(bullets([
"<b>Accelerated atherosclerosis:</b> hyperglycemia, dyslipidemia, and insulin resistance promote endothelial dysfunction, advanced glycation end-products (AGEs), and inflammation → accelerated coronary artery disease.",
"<b>Diabetic cardiomyopathy:</b> myocardial dysfunction independent of coronary disease/hypertension, driven by lipotoxicity, myocardial fibrosis, mitochondrial dysfunction, and AGE cross-linking — manifests as diastolic dysfunction progressing to heart failure.",
"<b>Silent myocardial ischemia:</b> autonomic neuropathy blunts anginal pain perception → higher risk of unrecognized MI.",
"<b>Autonomic neuropathy:</b> resting tachycardia, orthostatic hypotension, reduced heart rate variability.",
"<b>Heart failure:</b> diabetics have 2–4x increased risk of heart failure (both HFrEF and HFpEF).",
"<b>Management:</b> aggressive risk factor control (statins, BP control), SGLT2 inhibitors (proven cardiovascular/heart failure benefit), GLP-1 receptor agonists (proven MACE reduction), antiplatelet therapy where indicated.",
]))
story.append(PageBreak())
# ============================================================
# 9. NAFLD - DETAILED
# ============================================================
story.append(section(9, "Non-Alcoholic Fatty Liver Disease (NAFLD) — Detailed"))
story.append(sub("Definition and Epidemiology"))
story.append(P("NAFLD is defined as hepatic steatosis (fat in >5% of hepatocytes) on imaging or biopsy in the absence of significant alcohol use or other secondary causes of fat accumulation. It is now the most common chronic liver disease worldwide and is present in up to 55-70% of people with type 2 diabetes, reflecting the shared driver of insulin resistance."))
story.append(sub("Pathophysiology"))
story.append(subsub("The 'Multiple-Hit' Model"))
story.append(bullets([
"<b>Insulin resistance</b> is central: it impairs suppression of adipose tissue lipolysis → increased free fatty acid (FFA) flux to the liver.",
"Hyperinsulinemia also directly stimulates hepatic <b>de novo lipogenesis</b> via SREBP-1c activation, and impairs fatty acid oxidation.",
"Excess FFAs accumulate as hepatic triglyceride (simple steatosis) — the 'first hit'.",
"<b>Lipotoxicity:</b> toxic lipid intermediates (diacylglycerol, ceramides, free cholesterol - not triglyceride itself) cause mitochondrial dysfunction, ER stress, and oxidative stress ('second hit').",
"This drives hepatocyte injury (ballooning), activation of Kupffer cells and hepatic stellate cells, and an inflammatory/fibrogenic response → progression from simple fatty liver to <b>steatohepatitis (NASH)</b>.",
"Gut-derived factors (dysbiosis, increased intestinal permeability/endotoxin) and genetic polymorphisms (e.g., PNPLA3, TM6SF2) modulate individual risk and rate of progression.",
]))
story.append(sub("Spectrum / Stages of Disease"))
story.append(make_table(
["Stage", "Features"],
[
["NAFL (simple steatosis)", "Hepatic fat accumulation without significant inflammation or hepatocyte injury; generally benign, slow progression"],
["NASH (non-alcoholic steatohepatitis)", "Steatosis + lobular inflammation + hepatocyte ballooning injury +/- Mallory-Denk bodies; can progress to fibrosis"],
["Fibrosis (F1-F4)", "Progressive peri-sinusoidal/portal fibrosis from NASH; F4 = cirrhosis"],
["Cirrhosis", "End-stage fibrosis with architectural distortion; risk of decompensation and portal hypertension"],
["Hepatocellular carcinoma (HCC)", "Can arise from NASH-cirrhosis, and occasionally from NASH without cirrhosis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(sub("Risk Factors"))
story.append(bullets([
"Type 2 diabetes mellitus and insulin resistance (strongest associations).",
"Obesity, especially visceral/central adiposity.",
"Metabolic syndrome (dyslipidemia - especially high triglycerides/low HDL, hypertension).",
"Polycystic ovary syndrome, hypothyroidism, obstructive sleep apnea (associated conditions).",
]))
story.append(sub("Clinical Features"))
story.append(bullets([
"Usually asymptomatic; may have vague right upper quadrant discomfort or fatigue.",
"Hepatomegaly may be present on examination.",
"Signs of cirrhosis (spider angiomata, palmar erythema, ascites, jaundice) only in advanced disease.",
]))
story.append(sub("Diagnosis"))
story.append(bullets([
"<b>Liver enzymes:</b> mild elevation of ALT and AST, typically ALT > AST (reverses toward AST-predominant as fibrosis/cirrhosis develops); enzymes can also be entirely normal.",
"<b>Imaging:</b> ultrasound (hyperechoic 'bright liver', first-line, but insensitive for mild steatosis); CT/MRI more sensitive; <b>MRI-PDFF</b> is the most accurate non-invasive quantifier of fat.",
"<b>Non-invasive fibrosis scores:</b> FIB-4 index and NAFLD Fibrosis Score (NFS) using age, BMI, platelets, albumin, AST/ALT — used to risk-stratify and decide who needs specialist referral or biopsy.",
"<b>Transient elastography (FibroScan)</b> and MR elastography — assess liver stiffness as a surrogate for fibrosis.",
"<b>Liver biopsy</b> — gold standard; required to definitively diagnose NASH and stage fibrosis, but invasive; reserved for diagnostic uncertainty or when it will change management.",
]))
story.append(sub("Management"))
story.append(bullets([
"<b>Weight loss</b> — the cornerstone of treatment; 7-10% body weight loss improves steatosis, inflammation, and can regress fibrosis; >10% loss shown to induce NASH resolution in many patients.",
"<b>Glycemic control</b> — optimize diabetes management; poor glycemic control accelerates progression.",
"<b>Pioglitazone</b> — improves hepatic histology (steatosis and inflammation) in biopsy-proven NASH, including in diabetics; weight gain and fluid retention are trade-offs.",
"<b>GLP-1 receptor agonists</b> (liraglutide, semaglutide) — promote weight loss and have shown histological improvement in NASH trials.",
"<b>Vitamin E</b> — may be used in non-diabetic biopsy-proven NASH (antioxidant effect); use is more controversial in diabetics.",
"Avoid alcohol; manage dyslipidemia (statins are safe in NAFLD/NASH and do not need to be withheld); bariatric surgery can be considered in eligible obese patients and improves/resolves NASH in many.",
"Screen for and manage cardiovascular risk — cardiovascular disease, not liver disease, is the leading cause of death in NAFLD patients.",
"Surveillance for hepatocellular carcinoma and varices once cirrhosis develops.",
]))
story.append(PageBreak())
# ============================================================
# 10. IDM - RESTRUCTURED (Mother + Fetus + Baby)
# ============================================================
story.append(section(10, "Infant of a Diabetic Mother (IDM)"))
story.append(sub("Pathophysiology — The Pedersen Hypothesis"))
story.append(P("Maternal hyperglycemia crosses the placenta freely (glucose crosses; maternal insulin does not). This exposes the fetus to chronically elevated glucose → fetal pancreatic beta-cell hyperplasia → <b>fetal hyperinsulinemia</b>. Because insulin is a potent fetal growth factor, this single mechanism (fetal hyperinsulinemia) underlies almost all classic complications of IDM — both during pregnancy and after birth."))
story.append(sub("A. Complications to the Mother (during pregnancy)"))
story.append(bullets([
"<b>Pre-eclampsia / gestational hypertension</b> — 2-4x more common in diabetic pregnancies, especially with pre-existing vascular disease.",
"<b>Polyhydramnios</b> — fetal hyperglycemia causes fetal polyuria, increasing amniotic fluid volume; raises risk of preterm labor and malpresentation.",
"<b>Worsening of maternal diabetic retinopathy and nephropathy</b> — pregnancy can accelerate progression of existing microvascular disease.",
"<b>Diabetic ketoacidosis (DKA)</b> — pregnancy is a ketogenic state; DKA can occur at lower glucose thresholds than in non-pregnant patients and is dangerous for both mother and fetus.",
"<b>Increased infection risk</b> — urinary tract infections, candidiasis.",
"<b>Obstructed/prolonged labor and operative delivery</b> — due to fetal macrosomia; increased rates of Cesarean section.",
"<b>Postpartum hemorrhage</b> — from uterine overdistension (polyhydramnios/macrosomia) and prolonged labor.",
]))
story.append(sub("B. Complications to the Fetus (during pregnancy / at birth)"))
story.append(bullets([
"<b>Macrosomia</b> (birth weight >4 kg or >90th percentile) — fetal hyperinsulinemia drives excess growth of insulin-sensitive tissues (fat, muscle, organomegaly), sparing the brain — classic asymmetric growth with increased shoulder/trunk size predisposing to <b>shoulder dystocia</b> and birth trauma (brachial plexus injury, clavicle fracture).",
"<b>Congenital malformations</b> (2-4x general population risk) — related to poor glycemic control during organogenesis (first trimester, weeks 3-8): cardiac defects (VSD, transposition of the great vessels), neural tube defects, and the classic but rare <b>caudal regression syndrome (sacral agenesis)</b>.",
"<b>Intrauterine growth restriction (IUGR)</b> — can occur instead of macrosomia if the mother has advanced vascular disease (placental insufficiency).",
"<b>Unexplained stillbirth</b> — risk increased with poor glycemic control, especially in the third trimester.",
"<b>Fetal hypoxia</b> — chronic hyperglycemia increases fetal oxygen consumption and can cause relative intrauterine hypoxia, stimulating erythropoietin and polycythemia.",
]))
story.append(sub("C. Treatment / Management of the Mother During Pregnancy"))
story.append(bullets([
"<b>Preconception counseling</b> — optimize HbA1c (target <6.5% ideally) before conception to reduce malformation risk; start high-dose folic acid.",
"<b>Glycemic targets in pregnancy</b> — tighter than usual: fasting <95 mg/dL, 1-hr postprandial <140 mg/dL, 2-hr postprandial <120 mg/dL.",
"<b>Insulin is the preferred pharmacologic agent in pregnancy</b> (does not cross the placenta in clinically significant amounts); doses typically need to increase progressively through pregnancy due to rising insulin resistance from placental hormones (human placental lactogen, cortisol, progesterone).",
"Metformin and glyburide are sometimes used (particularly in gestational diabetes) but insulin remains first-line/preferred, especially in pre-existing diabetes.",
"<b>Self-monitoring of blood glucose</b> multiple times daily; regular HbA1c monitoring.",
"<b>Ophthalmologic exam</b> each trimester (risk of retinopathy progression); renal function monitoring.",
"<b>Nutrition/dietary counseling</b> and regular physical activity as tolerated.",
"Low-dose aspirin from the end of the first trimester to reduce pre-eclampsia risk (standard for pregestational diabetes).",
]))
story.append(sub("D. Monitoring / Treatment of the Fetus During Pregnancy"))
story.append(bullets([
"<b>Serial growth ultrasounds</b> — monitor for macrosomia or growth restriction, and amniotic fluid volume (polyhydramnios).",
"<b>Fetal echocardiography</b> — offered given increased risk of congenital heart defects.",
"<b>Antenatal fetal surveillance</b> in the third trimester — non-stress tests (NST), biophysical profile, umbilical artery Doppler if growth-restricted.",
"<b>Timing of delivery</b> — individualized; often delivery is planned around 39-40 weeks (earlier if poor control, macrosomia, or other complications) to balance risks of stillbirth against prematurity.",
"Consideration of elective Cesarean section if estimated fetal weight is very high, to reduce shoulder dystocia risk.",
]))
story.append(sub("E. Management of the Baby After Birth (Neonatal Period)"))
story.append(bullets([
"<b>Neonatal hypoglycemia</b> — the most important immediate risk: after cord clamping, the maternal glucose supply stops abruptly but fetal hyperinsulinemia persists for hours to days → profound hypoglycemia. Manage with early feeding within the first hour, frequent bedside glucose monitoring (per protocol, e.g., at 30 min, 1, 2, 4, 6, 12, 24 hours), and IV dextrose if symptomatic or glucose remains low despite feeding.",
"<b>Respiratory distress syndrome (RDS)</b> — fetal hyperinsulinemia antagonizes cortisol's stimulation of surfactant production, delaying lung maturity even at term; monitor respiratory status closely and support as needed (may require surfactant/NICU care).",
"<b>Hypertrophic cardiomyopathy</b> — transient septal/ventricular wall thickening from hyperinsulinemia; usually resolves over weeks to months; echocardiogram if murmur or respiratory/feeding difficulty.",
"<b>Polycythemia</b> — from chronic relative intrauterine hypoxia driving erythropoietin; monitor hematocrit; partial exchange transfusion rarely needed for severe symptomatic cases.",
"<b>Hyperbilirubinemia/jaundice</b> — from breakdown of excess red cells (polycythemia) and immature hepatic conjugation; monitor bilirubin, treat with phototherapy as needed.",
"<b>Hypocalcemia and hypomagnesemia</b> — due to delayed parathyroid hormone response; monitor calcium/magnesium, supplement if symptomatic (jitteriness, seizures).",
"<b>Birth injury</b> from macrosomia/shoulder dystocia — examine for brachial plexus injury (Erb's palsy), clavicle fracture, cephalohematoma.",
"<b>Screen for congenital anomalies</b> if not already characterized antenatally (cardiac exam/echo, spine exam).",
"Longer-term: IDM babies have increased lifetime risk of obesity, impaired glucose tolerance, and type 2 diabetes themselves — anticipatory guidance for the family."
]))
story.append(Spacer(1, 20))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#B0B0B0")))
story.append(Spacer(1, 6))
story.append(Paragraph(
"<i>This study guide is compiled from standard medical education content for exam preparation purposes. "
"Always verify current clinical guidelines and drug dosing against up-to-date primary sources before clinical application.</i>",
styles["Body"]
))
def add_page_number(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.setFillColor(colors.grey)
canvas.drawCentredString(A4[0] / 2, 1.2 * cm, f"Page {doc.page} | Diabetes Mellitus Study Guide")
canvas.restoreState()
doc = SimpleDocTemplate(
OUT, pagesize=A4,
topMargin=1.8*cm, bottomMargin=1.8*cm, leftMargin=1.8*cm, rightMargin=1.8*cm,
title="Diabetes Mellitus Study Guide"
)
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
print("PDF written to", OUT)
cd /tmp/workspace/diabetes-study-guide && python3 build_pdf.py && ls -la Diabetes_Mellitus_Study_Guide.pdf
Diabetes Mellitus Study Guide
PDF Document · PDF
Make the downloadable pdf with the new version with these added 4 sections
ls -la /tmp/workspace/diabetes-study-guide/Diabetes_Mellitus_Study_Guide.pdf && python3 -c " from pypdf import PdfReader r = PdfReader('/tmp/workspace/diabetes-study-guide/Diabetes_Mellitus_Study_Guide.pdf') print('Pages:', len(r.pages)) "
ls -la /tmp/workspace/diabetes-study-guide/ && ls -la /tmp/workspace/diabetes-study-guide/images/ 2>/dev/null | head -20
rm -f /tmp/workspace/diabetes-study-guide/build_pdf.py && mkdir -p /tmp/workspace/diabetes-study-guide/images && cd /tmp/workspace/diabetes-study-guide/images && \ curl -sL -o npdr_pdr_compare.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_2be7acb9c280d151e627d68e4d67db96939457ea08afa1591c71079c3124df10.jpg" && \ curl -sL -o dr_progression_multipanel.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_11fce460ab92b396a501a2e6e961014e77f6ce88252a6d0e96fa94b56c26ca5c.jpg" && \ curl -sL -o dr_fa_progression.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_633087b66ecedb67128377f2a64a1f5128010817500c31611926c4b716c7923d.jpg" && \ curl -sL -o dme_oct_scan.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_0ef69763407fdb8c37908f5e83920636752f56a23867f6b355003018f4f70676.jpg" && \ curl -sL -o dme_oct_progression.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_69d9f43e87a21b7cb607dc278c219af9decbcf31bbc497c1380be2ff80cdb122.jpg" && \ curl -sL -o ocular_pathology_compare.jpg "https://cdn.orris.care/cdss_images/pmc_clinical_VQA_4bd236109668526070c698c92b7cc4350e2df49e12f7b7f525df047f3fa4f427.jpg" && \ ls -la
~/diabetes-study-guide/make_flowcharts.py
#!/usr/bin/env python3
"""Generate flowchart diagrams for insulin formation and glucose metabolism using matplotlib."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
import os
OUTDIR = "/tmp/workspace/diabetes-study-guide/images"
os.makedirs(OUTDIR, exist_ok=True)
BLUE = "#1a3d5c"
LIGHT = "#EEF3F7"
GREEN = "#2e7d32"
ORANGE = "#c0622a"
def box(ax, x, y, w, h, text, fc=LIGHT, ec=BLUE, fontsize=9.5, fontcolor="black", weight="normal"):
b = FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.08",
linewidth=1.4, edgecolor=ec, facecolor=fc)
ax.add_patch(b)
ax.text(x + w/2, y + h/2, text, ha="center", va="center", fontsize=fontsize,
color=fontcolor, weight=weight, wrap=True)
def arrow(ax, x1, y1, x2, y2, color=BLUE):
a = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle="-|>", mutation_scale=16,
linewidth=1.6, color=color)
ax.add_patch(a)
# ---------------------------------------------------------------
# FLOWCHART 1: Insulin Formation (Biosynthesis pathway)
# ---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(9, 11))
ax.set_xlim(0, 10)
ax.set_ylim(0, 22)
ax.axis("off")
ax.set_title("Insulin Formation (Biosynthesis in the Pancreatic Beta Cell)", fontsize=13, weight="bold", color=BLUE, pad=14)
steps = [
"INSULIN GENE (Chromosome 11)\nTranscription in beta-cell nucleus",
"mRNA\nTranslated on rough ER ribosomes",
"PREPROINSULIN\n(signal peptide + B-chain + C-peptide + A-chain)",
"Signal peptide cleaved in ER lumen",
"PROINSULIN\n(single chain: B-chain - C-peptide - A-chain,\nfolded with 2 disulfide bonds)",
"Transported to Golgi apparatus\nPackaged into immature secretory granules",
"Cleavage by Prohormone Convertases\n(PC1/3, PC2) + Carboxypeptidase E",
"MATURE INSULIN (A-chain + B-chain, disulfide-linked)\n+ C-PEPTIDE (released in EQUIMOLAR amounts)",
"Stored in mature secretory granules\nawaiting glucose-triggered exocytosis",
]
n = len(steps)
top = 20.5
gap = 2.35
h = 1.7
w = 8.6
x0 = 0.7
for i, s in enumerate(steps):
y = top - i * gap
fc = LIGHT
fontcolor = "black"
if i == 2 or i == 4:
fc = "#D6E4EF"
if i == 7:
fc = BLUE
fontcolor = "white"
box(ax, x0, y, w, h, s, fc=fc, fontcolor=fontcolor, weight="bold" if i in (0,2,4,7) else "normal")
if i < n - 1:
arrow(ax, x0 + w/2, y, x0 + w/2, y - (gap - h))
plt.tight_layout()
plt.savefig(f"{OUTDIR}/flowchart_insulin_formation.png", dpi=180, bbox_inches="tight")
plt.close()
# ---------------------------------------------------------------
# FLOWCHART 2: Glucose-triggered Insulin Secretion (Beta cell)
# ---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(9, 11))
ax.set_xlim(0, 10)
ax.set_ylim(0, 22)
ax.axis("off")
ax.set_title("Glucose-Triggered Insulin Secretion (Pancreatic Beta Cell)", fontsize=13, weight="bold", color=BLUE, pad=14)
steps2 = [
"Rise in blood GLUCOSE",
"Glucose enters beta cell via GLUT2 transporter",
"GLUCOKINASE phosphorylates glucose\n(rate-limiting 'glucose sensor' step)",
"Glycolysis + oxidative metabolism\n\u2191 ATP : ADP ratio",
"ATP-sensitive K+ channel (K-ATP: SUR1/Kir6.2) CLOSES",
"Membrane DEPOLARIZATION",
"Voltage-gated Ca2+ channels OPEN\n\u2192 Ca2+ influx",
"Exocytosis of insulin secretory granules",
"INSULIN + C-PEPTIDE released into blood\n(biphasic: rapid 1st phase + sustained 2nd phase)",
]
n2 = len(steps2)
for i, s in enumerate(steps2):
y = top - i * gap
fc = LIGHT
fontcolor = "black"
weight = "normal"
if i == 0:
fc = ORANGE; fontcolor = "white"; weight = "bold"
if i == 4 or i == 6:
fc = "#D6E4EF"; weight = "bold"
if i == 8:
fc = BLUE; fontcolor = "white"; weight = "bold"
box(ax, x0, y, w, h, s, fc=fc, fontcolor=fontcolor, weight=weight)
if i < n2 - 1:
arrow(ax, x0 + w/2, y, x0 + w/2, y - (gap - h))
plt.tight_layout()
plt.savefig(f"{OUTDIR}/flowchart_insulin_secretion.png", dpi=180, bbox_inches="tight")
plt.close()
# ---------------------------------------------------------------
# FLOWCHART 3: Insulin Signaling and Glucose Metabolism (target cell)
# ---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(10, 12))
ax.set_xlim(0, 12)
ax.set_ylim(0, 16)
ax.axis("off")
ax.set_title("Insulin Signaling Pathway and Effects on Glucose Metabolism\n(Muscle / Adipose / Liver)", fontsize=13, weight="bold", color=BLUE, pad=14)
box(ax, 3.7, 14.0, 4.6, 1.3, "INSULIN binds\nINSULIN RECEPTOR (tyrosine kinase)", fc=BLUE, fontcolor="white", weight="bold")
arrow(ax, 6.0, 14.0, 6.0, 12.9)
box(ax, 3.7, 11.6, 4.6, 1.3, "Receptor autophosphorylation\n\u2192 activates IRS-1 / IRS-2", fc=LIGHT, weight="bold")
arrow(ax, 6.0, 11.6, 6.0, 10.5)
box(ax, 3.7, 9.2, 4.6, 1.3, "PI3K \u2192 Akt (PKB) activation", fc="#D6E4EF", weight="bold")
arrow(ax, 6.0, 9.2, 6.0, 8.1)
box(ax, 3.7, 6.8, 4.6, 1.3, "GLUT4 translocation to cell membrane", fc=LIGHT, weight="bold")
arrow(ax, 6.0, 6.8, 6.0, 5.7)
box(ax, 3.7, 4.4, 4.6, 1.3, "GLUCOSE UPTAKE into cell", fc=GREEN, fontcolor="white", weight="bold")
arrow(ax, 8.3, 12.25, 9.6, 12.25, color=ORANGE)
box(ax, 9.6, 11.6, 2.2, 1.3, "Ras/MAPK\npathway\n(growth effects)", fc="#FBE7DA", ec=ORANGE, fontsize=8.5)
arrow(ax, 3.7, 5.05, 1.6, 5.05, color=BLUE)
box(ax, 0.2, 5.6, 3.0, 1.1, "Stimulatory effects", fc=GREEN, fontcolor="white", fontsize=9, weight="bold")
arrow(ax, 1.7, 5.6, 1.7, 4.1)
box(ax, 0.2, 3.0, 3.0, 1.1, "\u2191 Glycolysis\n(hexokinase, PFK-1, pyruvate kinase)", fontsize=8.3)
arrow(ax, 1.7, 3.0, 1.7, 2.1)
box(ax, 0.2, 0.9, 3.0, 1.1, "\u2191 Glycogenesis (glycogen synthase)\n\u2191 Lipogenesis (ACC, FAS)", fontsize=8.3)
arrow(ax, 8.3, 5.05, 10.4, 5.05, color=ORANGE)
box(ax, 8.4, 5.6, 3.4, 1.1, "Inhibitory effects", fc=ORANGE, fontcolor="white", fontsize=9, weight="bold")
arrow(ax, 10.1, 5.6, 10.1, 4.1)
box(ax, 8.4, 3.0, 3.4, 1.1, "\u2193 Gluconeogenesis\n(\u2193PEPCK, F1,6BPase, G6Pase)", fontsize=8.3)
arrow(ax, 10.1, 3.0, 10.1, 2.1)
box(ax, 8.4, 0.9, 3.4, 1.1, "\u2193 Glycogenolysis\n\u2193 Lipolysis (\u2193HSL) \u2193 Proteolysis", fontsize=8.3)
plt.tight_layout()
plt.savefig(f"{OUTDIR}/flowchart_insulin_signaling.png", dpi=180, bbox_inches="tight")
plt.close()
print("Flowcharts generated successfully in", OUTDIR)
cd /tmp/workspace/diabetes-study-guide && python3 make_flowcharts.py && ls -la images/
~/diabetes-study-guide/build_pdf.py
#!/usr/bin/env python3
"""Build the Diabetes Mellitus Study Guide PDF - v2 (flowcharts, eye images, expanded NAFLD & IDM)."""
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
PageBreak, ListFlowable, ListItem, HRFlowable, Image
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from PIL import Image as PILImage
BASE = "/tmp/workspace/diabetes-study-guide"
IMG = f"{BASE}/images"
OUT = f"{BASE}/Diabetes_Mellitus_Study_Guide.pdf"
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="TitleBig", fontSize=24, leading=28, alignment=TA_CENTER,
textColor=colors.HexColor("#1a3d5c"), spaceAfter=6, fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Subtitle", fontSize=13, leading=16, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), spaceAfter=20, fontName="Helvetica"))
styles.add(ParagraphStyle(name="SectionHeading", fontSize=16, leading=20, spaceBefore=14, spaceAfter=8,
textColor=colors.white, backColor=colors.HexColor("#1a3d5c"),
fontName="Helvetica-Bold", leftIndent=6, borderPadding=6))
styles.add(ParagraphStyle(name="SubHeading", fontSize=12.5, leading=15, spaceBefore=10, spaceAfter=4,
textColor=colors.HexColor("#1a3d5c"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="SubSubHeading", fontSize=11, leading=13, spaceBefore=8, spaceAfter=3,
textColor=colors.HexColor("#c0622a"), fontName="Helvetica-Bold"))
styles.add(ParagraphStyle(name="Body", fontSize=10, leading=14, spaceAfter=4, alignment=TA_LEFT, fontName="Helvetica"))
styles.add(ParagraphStyle(name="BulletBody", fontSize=10, leading=13.5, spaceAfter=2, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TOCItem", fontSize=11, leading=18, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableCell", fontSize=8.7, leading=11, fontName="Helvetica"))
styles.add(ParagraphStyle(name="TableHeader", fontSize=9, leading=11, fontName="Helvetica-Bold", textColor=colors.white))
styles.add(ParagraphStyle(name="Caption", fontSize=8.5, leading=10.5, alignment=TA_CENTER,
textColor=colors.HexColor("#4a4a4a"), fontName="Helvetica-Oblique", spaceAfter=10))
def P(text):
return Paragraph(text, styles["Body"])
def bullets(items):
return ListFlowable(
[ListItem(Paragraph(i, styles["BulletBody"]), leftIndent=6) for i in items],
bulletType="bullet", start="•", leftIndent=14, spaceBefore=2, spaceAfter=6
)
def make_table(header, rows, col_widths=None):
data = [[Paragraph(h, styles["TableHeader"]) for h in header]]
for r in rows:
data.append([Paragraph(str(c), styles["TableCell"]) for c in r])
t = Table(data, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1a3d5c")),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#B0B0B0")),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#EEF3F7")]),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]))
return t
def section(num, title):
return Paragraph(f"{num}. {title}", styles["SectionHeading"])
def sub(title):
return Paragraph(title, styles["SubHeading"])
def subsub(title):
return Paragraph(title, styles["SubSubHeading"])
def fig(path, max_width_cm=16.5, caption=None):
im = PILImage.open(path)
w, h = im.size
max_w = max_width_cm * cm
scale = max_w / w
max_h = 21 * cm
disp_w = max_w
disp_h = h * scale
if disp_h > max_h:
disp_h = max_h
disp_w = w * (max_h / h)
flow = [Image(path, width=disp_w, height=disp_h)]
if caption:
flow.append(Paragraph(caption, styles["Caption"]))
return flow
story = []
story.append(Spacer(1, 3.2 * cm))
story.append(Paragraph("Diabetes Mellitus", styles["TitleBig"]))
story.append(Paragraph("Complete Study Guide", styles["TitleBig"]))
story.append(Paragraph("Biochemistry · Diagnosis · Pharmacology · Complications · Special Populations", styles["Subtitle"]))
story.append(Spacer(1, 1*cm))
story.append(HRFlowable(width="80%", thickness=1, color=colors.HexColor("#1a3d5c"), hAlign="CENTER"))
story.append(Spacer(1, 1*cm))
toc_items = [
"1. Biochemistry of Insulin Formation and Glucose Metabolism (with flowcharts)",
"2. Diagnosis of Diabetes Mellitus — Tests, Markers, Values",
"3. Pharmacological Drugs — Classification and Receptors",
"4. Types of Insulin Supplements",
"5. Diabetic Retinopathy and Other Diabetic Eye Disease (with images)",
"6. Diabetic Nephropathy",
"7. Diabetic Foot",
"8. Cardiac Associations of Diabetes Mellitus",
"9. Non-Alcoholic Fatty Liver Disease (NAFLD) — Detailed",
"10. Infant of a Diabetic Mother (IDM) — Maternal & Fetal Complications and Management",
]
story.append(Paragraph("Contents (Correct Study Order)", styles["SubHeading"]))
for item in toc_items:
story.append(Paragraph(item, styles["TOCItem"]))
story.append(PageBreak())
story.append(section(1, "Biochemistry of Insulin Formation and Glucose Metabolism"))
story.append(sub("Insulin Synthesis"))
story.append(bullets([
"Insulin gene (chromosome 11) transcribed in pancreatic beta cells → mRNA translated into <b>preproinsulin</b> on rough ER ribosomes.",
"Signal peptide cleaved → <b>proinsulin</b> (single chain: A-chain, B-chain, connecting C-peptide, held by 2 disulfide bonds).",
"Proinsulin transported to Golgi, packaged into secretory granules, cleaved by prohormone convertases (PC1/3, PC2) and carboxypeptidase E → <b>insulin (A+B chains linked by disulfide bonds) + C-peptide</b> in equimolar amounts.",
"C-peptide has no known metabolic activity but is a useful clinical marker of endogenous insulin production (unaffected by exogenous insulin injections).",
]))
story.extend(fig(f"{IMG}/flowchart_insulin_formation.png", max_width_cm=11,
caption="Flowchart 1: Insulin biosynthesis pathway from gene transcription to mature hormone."))
story.append(sub("Insulin Secretion Mechanism (Beta Cell)"))
story.append(bullets([
"Glucose enters the beta cell via the <b>GLUT2</b> transporter.",
"Glucokinase phosphorylates glucose (rate-limiting "glucose sensor" step).",
"Glycolysis/oxidative metabolism raises the ATP:ADP ratio.",
"ATP closes <b>ATP-sensitive K+ channels (K<sub>ATP</sub>: SUR1/Kir6.2 subunits)</b> → membrane depolarization.",
"Voltage-gated Ca2+ channels open → Ca2+ influx → triggers exocytosis of insulin granules.",
"Biphasic release: first phase (stored granules, rapid) and second phase (newly synthesized insulin, sustained).",
]))
story.append(PageBreak())
story.extend(fig(f"{IMG}/flowchart_insulin_secretion.png", max_width_cm=11,
caption="Flowchart 2: Glucose-stimulated insulin secretion pathway in the pancreatic beta cell."))
story.append(sub("Insulin Receptor and Signaling"))
story.append(bullets([
"Insulin receptor: tetrameric transmembrane <b>receptor tyrosine kinase</b> (2 alpha + 2 beta subunits).",
"Insulin binding → autophosphorylation of beta subunits → phosphorylates <b>IRS-1/IRS-2</b> → activates <b>PI3K/Akt pathway</b> → triggers <b>GLUT4 translocation</b> to the cell membrane in muscle/adipose tissue → glucose uptake.",
"A parallel <b>Ras/MAPK pathway</b> mediates insulin's growth/mitogenic effects.",
]))
story.append(PageBreak())
story.extend(fig(f"{IMG}/flowchart_insulin_signaling.png", max_width_cm=15,
caption="Flowchart 3: Insulin receptor signal transduction and downstream effects on glucose, glycogen, and lipid metabolism."))
story.append(sub("Glucose Metabolism — Insulin's Actions (Summary Table)"))
story.append(make_table(
["Pathway", "Effect of Insulin"],
[
["Glycolysis", "Stimulates (hexokinase, PFK-1, pyruvate kinase induction)"],
["Glycogenesis", "Stimulates (activates glycogen synthase)"],
["Glycogenolysis", "Inhibits"],
["Gluconeogenesis", "Inhibits (suppresses PEPCK, fructose-1,6-bisphosphatase, glucose-6-phosphatase)"],
["Lipogenesis", "Stimulates (activates acetyl-CoA carboxylase, fatty acid synthase)"],
["Lipolysis", "Inhibits (inhibits hormone-sensitive lipase)"],
["Proteolysis", "Inhibits; promotes protein synthesis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(Spacer(1, 6))
story.append(P("<b>Counter-regulatory hormones:</b> glucagon (stimulates glycogenolysis/gluconeogenesis via cAMP/PKA), epinephrine, cortisol, growth hormone — all raise blood glucose, opposing insulin."))
story.append(PageBreak())
story.append(section(2, "Diagnosis of Diabetes Mellitus — Tests, Markers, Values"))
story.append(P("Diagnostic criteria (ADA/WHO) — any one confirmed on two occasions (unless unequivocal hyperglycemia with symptoms):"))
story.append(make_table(
["Test", "Normal", "Prediabetes", "Diabetes"],
[
["Fasting Plasma Glucose (FPG)", "<100 mg/dL (5.6 mmol/L)", "100–125 mg/dL", "≥126 mg/dL (7.0 mmol/L)"],
["2-hr OGTT (75g glucose load)", "<140 mg/dL", "140–199 mg/dL", "≥200 mg/dL (11.1 mmol/L)"],
["HbA1c", "<5.7%", "5.7–6.4%", "≥6.5%"],
["Random Plasma Glucose + symptoms", "-", "-", "≥200 mg/dL"],
],
col_widths=[6*cm, 3.5*cm, 3.5*cm, 3.5*cm]
))
story.append(Spacer(1, 8))
story.append(sub("Gestational Diabetes Screening"))
story.append(P("24–28 weeks gestation, 75g OGTT (one-step): fasting ≥92, 1-hr ≥180, 2-hr ≥153 mg/dL (any one abnormal = GDM); or two-step approach with 50g screen followed by 100g OGTT."))
story.append(sub("Classification Markers"))
story.append(bullets([
"<b>Type 1 DM:</b> autoantibodies — GAD65, islet cell antibodies (ICA), IA-2 (insulinoma-associated antigen 2), insulin autoantibodies (IAA), ZnT8 antibodies. Low/absent C-peptide.",
"<b>Type 2 DM:</b> normal/high C-peptide (insulin resistance), no autoantibodies, associated with obesity/metabolic syndrome.",
"<b>MODY:</b> genetic (e.g., HNF1A, GCK mutations), autosomal dominant, young onset without autoimmunity.",
]))
story.append(sub("Other Markers"))
story.append(bullets([
"Urine glucose (glucosuria — renal threshold ~180 mg/dL).",
"Urine/serum ketones — diabetic ketoacidosis (Type 1).",
"Microalbuminuria (30–300 mg/24h) — early nephropathy marker.",
"C-peptide — differentiates endogenous vs exogenous insulin, assesses beta cell reserve.",
]))
story.append(PageBreak())
story.append(section(3, "Pharmacological Drugs — Classification and Receptors"))
story.append(make_table(
["Class", "Examples", "Mechanism / Receptor Target", "Key Side Effects"],
[
["Biguanides", "Metformin", "Activates AMPK; decreases hepatic gluconeogenesis, increases peripheral insulin sensitivity", "GI upset, lactic acidosis (rare), B12 deficiency"],
["Sulfonylureas", "Glibenclamide, Glipizide, Glimepiride", "Bind SUR1 subunit of K_ATP channel on beta cells → closes channel → insulin release", "Hypoglycemia, weight gain"],
["Meglitinides", "Repaglinide, Nateglinide", "Same K_ATP/SUR1 site, faster/shorter action", "Hypoglycemia (less than SU)"],
["Thiazolidinediones (TZDs)", "Pioglitazone, Rosiglitazone", "Activate PPAR-gamma nuclear receptor → improves insulin sensitivity in adipose/muscle", "Weight gain, fluid retention, heart failure risk, fracture risk"],
["Alpha-glucosidase inhibitors", "Acarbose, Miglitol", "Inhibit intestinal alpha-glucosidase → delay carbohydrate absorption", "Flatulence, GI upset"],
["DPP-4 inhibitors (gliptins)", "Sitagliptin, Vildagliptin, Linagliptin", "Inhibit dipeptidyl peptidase-4 → increases endogenous GLP-1/GIP levels", "Generally well tolerated; pancreatitis risk (rare)"],
["GLP-1 receptor agonists", "Exenatide, Liraglutide, Semaglutide, Dulaglutide", "Agonists at GLP-1 receptor → glucose-dependent insulin secretion, decreases glucagon, delays gastric emptying, satiety", "Nausea, vomiting, pancreatitis risk"],
["SGLT2 inhibitors", "Empagliflozin, Dapagliflozin, Canagliflozin", "Inhibit sodium-glucose cotransporter 2 in proximal renal tubule → glucosuria", "UTI, genital mycotic infections, euglycemic DKA"],
["Amylin analogs", "Pramlintide", "Mimics amylin, co-secreted with insulin — slows gastric emptying, suppresses glucagon", "Nausea, hypoglycemia (with insulin)"],
["Insulin", "See Section 4", "Insulin receptor (tyrosine kinase)", "Hypoglycemia, weight gain"],
],
col_widths=[3.4*cm, 3.6*cm, 6.8*cm, 2.7*cm]
))
story.append(PageBreak())
story.append(section(4, "Types of Insulin Supplements"))
story.append(make_table(
["Type", "Examples", "Onset", "Peak", "Duration"],
[
["Rapid-acting", "Lispro, Aspart, Glulisine", "10–15 min", "1–2 hr", "3–5 hr"],
["Short-acting (Regular)", "Regular human insulin", "30–60 min", "2–3 hr", "5–8 hr"],
["Intermediate-acting", "NPH (isophane)", "2–4 hr", "4–10 hr", "10–16 hr"],
["Long-acting", "Glargine, Detemir", "1–2 hr", "minimal peak", "20–24 hr"],
["Ultra-long-acting", "Degludec", "30–90 min", "minimal peak", "up to 42 hr"],
["Premixed", "70/30 NPH/Regular, 75/25 lispro protamine/lispro", "Combination profile", "Combination", "Combination"],
],
col_widths=[3.7*cm, 5.8*cm, 2.6*cm, 2.6*cm, 2.6*cm]
))
story.append(Spacer(1, 8))
story.append(P("<b>Clinical use:</b> rapid-acting insulin is used for prandial control (given with meals); long-acting/basal insulin provides background coverage; premixed formulations offer simplified regimens for select patients."))
story.append(PageBreak())
story.append(section(5, "Diabetic Retinopathy and Other Diabetic Eye Disease"))
story.append(sub("Pathophysiology"))
story.append(P("Chronic hyperglycemia causes pericyte loss, thickening of the retinal capillary basement membrane, and microvascular occlusion. The resulting retinal ischemia raises VEGF (vascular endothelial growth factor), which drives leakage and, later, abnormal new vessel growth."))
story.append(sub("Signs — Non-Proliferative Diabetic Retinopathy (NPDR)"))
story.append(bullets([
"<b>Microaneurysms</b> — earliest visible sign; small red dots from capillary wall outpouching.",
"<b>Dot-and-blot hemorrhages</b> — bleeding confined to deeper retinal layers.",
"<b>Hard exudates</b> — yellow-white lipid deposits from chronic leakage.",
"<b>Cotton wool spots</b> — pale, fluffy patches representing nerve fiber layer micro-infarcts (retinal ischemia).",
"<b>Venous beading</b> and <b>IRMA</b> (intraretinal microvascular abnormalities) — signs of worsening ischemia, seen in severe/pre-proliferative NPDR.",
]))
story.append(sub("Signs — Proliferative Diabetic Retinopathy (PDR)"))
story.append(bullets([
"<b>Neovascularization</b> at the disc (NVD) or elsewhere (NVE) — fragile new vessels growing in response to ischemia/VEGF.",
"<b>Vitreous hemorrhage</b> — from rupture of fragile new vessels.",
"<b>Fibrovascular proliferation</b> and <b>tractional retinal detachment</b> — end-stage complication.",
"<b>Laser photocoagulation scars</b> may be visible after treatment.",
]))
story.extend(fig(f"{IMG}/npdr_pdr_compare.jpg", max_width_cm=15,
caption="Fundus comparison: (A) NPDR with isolated hemorrhage and a cotton wool spot; (B) PDR with disc neovascularization, hard exudates, and macular exudation."))
story.extend(fig(f"{IMG}/dr_progression_multipanel.jpg", max_width_cm=15,
caption="Progression of diabetic retinopathy on fundus photography and OCT: microaneurysms/hemorrhages, clinically significant macular edema, cotton wool spots, venous beading, IRMA, neovascularization, pre-retinal/vitreous hemorrhage, and laser scars."))
story.append(PageBreak())
story.extend(fig(f"{IMG}/dr_fa_progression.jpg", max_width_cm=15,
caption="Fundus photographs and fluorescein angiography (FA) showing progression from moderate/severe NPDR to early and high-risk PDR, with vascular leakage and capillary non-perfusion (ischemia) on FA."))
story.append(sub("Diabetic Macular Edema (DME)"))
story.append(P("DME can occur at any stage of retinopathy and is a leading cause of vision loss in diabetics. It results from breakdown of the blood-retinal barrier causing fluid accumulation in the macula."))
story.extend(fig(f"{IMG}/dme_oct_scan.jpg", max_width_cm=13,
caption="OCT cross-section showing diabetic macular edema: retinal thickening, distorted foveal contour, and cystoid intraretinal fluid spaces."))
story.extend(fig(f"{IMG}/dme_oct_progression.jpg", max_width_cm=15,
caption="OCT series showing structural progression from a normal macula to diabetic macular edema and ischemic proliferative disease (cystic spaces, subretinal fluid, hard exudates, retinal thinning)."))
story.append(sub("Diagnosis"))
story.append(bullets([
"Dilated fundoscopic examination (annual screening for all diabetics).",
"Fundus fluorescein angiography (FA) — detects leakage, neovascularization, and capillary non-perfusion.",
"Optical coherence tomography (OCT) — quantifies macular thickness and detects fluid/cystic changes in DME.",
]))
story.append(sub("Management"))
story.append(bullets([
"Strict glycemic and blood pressure control (slows progression at every stage).",
"<b>Panretinal laser photocoagulation</b> for PDR.",
"<b>Focal/grid laser</b> or <b>anti-VEGF intravitreal injections</b> (ranibizumab, bevacizumab, aflibercept) for macular edema.",
"Vitrectomy for vitreous hemorrhage or tractional retinal detachment.",
]))
story.append(PageBreak())
story.append(sub("Other Diabetic Eye Disease (Beyond Retinopathy)"))
story.append(subsub("Diabetic Cataract"))
story.append(bullets([
"Diabetics develop cataracts earlier and more frequently than non-diabetics.",
"Mechanism: chronic hyperglycemia → increased flux through the polyol pathway → sorbitol accumulation in the lens → osmotic swelling and oxidative damage to lens fibers → opacification.",
"Presents as generalized lens haziness reducing visualization of retinal details, and blurred vision.",
]))
story.append(subsub("Diabetic Papillopathy"))
story.append(P("Mild, often self-limiting swelling of the optic disc seen in some diabetics; must be distinguished from more serious causes of disc edema."))
story.append(subsub("Neovascular Glaucoma"))
story.append(P("A severe complication of long-standing ischemic PDR: VEGF-driven new vessels grow over the iris and into the anterior chamber angle (rubeosis iridis), blocking aqueous outflow and causing a markedly elevated, difficult-to-control intraocular pressure."))
story.append(subsub("Third, Fourth, and Sixth Cranial Nerve Palsies"))
story.append(P("Diabetic mononeuropathy can cause an acute, painful third nerve palsy (classically pupil-sparing, due to ischemia of the central fascicles with sparing of peripherally located pupillary fibers), or isolated fourth/sixth nerve palsies causing diplopia."))
story.extend(fig(f"{IMG}/ocular_pathology_compare.jpg", max_width_cm=15,
caption="Comparative fundus panel: age-related macular degeneration, cataract (generalized haziness), diabetic retinopathy, glaucoma (disc cupping), hypertensive retinopathy, and a normal eye for reference."))
story.append(PageBreak())
story.append(section(6, "Diabetic Nephropathy"))
story.append(bullets([
"<b>Pathophysiology:</b> glomerular hyperfiltration (early) → mesangial matrix expansion → glomerular basement membrane thickening → <b>Kimmelstiel-Wilson nodules</b> (nodular glomerulosclerosis, pathognomonic) → progressive glomerulosclerosis.",
"<b>Stages:</b> hyperfiltration → microalbuminuria (30–300 mg/24h) → overt/macroalbuminuria (>300 mg/24h) → declining GFR → ESRD.",
"<b>Screening:</b> annual urine albumin-to-creatinine ratio (ACR) and eGFR, starting at diagnosis (T2DM) or 5 years post-diagnosis (T1DM).",
"<b>Management:</b> strict glycemic control, BP control (target <130/80), ACE inhibitors/ARBs (reduce intraglomerular pressure), SGLT2 inhibitors (proven renal protective effect independent of glycemic control), protein restriction in advanced CKD.",
]))
story.append(PageBreak())
story.append(section(7, "Diabetic Foot"))
story.append(bullets([
"<b>Pathophysiology:</b> triad of (1) peripheral neuropathy (sensory loss = loss of protective sensation, motor neuropathy = foot deformity, autonomic neuropathy = dry skin/reduced sweating), (2) peripheral arterial disease (macrovascular ischemia), (3) immunopathy (impaired leukocyte function → susceptibility to infection).",
"<b>Clinical features:</b> painless ulcers (typically over pressure points — metatarsal heads, heel), callus formation, <b>Charcot foot</b> (neuropathic joint destruction, rocker-bottom deformity), gangrene.",
"<b>Classification:</b> Wagner classification (grade 0–5, based on depth/tissue loss/gangrene) or University of Texas classification (grade + stage for infection/ischemia).",
"<b>Diagnosis:</b> 10g Semmes-Weinstein monofilament testing, vibration perception (biothesiometer), ankle-brachial index (ABI) for arterial disease, probe-to-bone test for osteomyelitis, imaging (X-ray/MRI).",
"<b>Management:</b> regular foot inspection, offloading devices, wound debridement, infection control (antibiotics), revascularization if ischemic, patient education, appropriate footwear.",
]))
story.append(PageBreak())
story.append(section(8, "Cardiac Associations of Diabetes Mellitus"))
story.append(bullets([
"<b>Accelerated atherosclerosis:</b> hyperglycemia, dyslipidemia, and insulin resistance promote endothelial dysfunction, advanced glycation end-products (AGEs), and inflammation → accelerated coronary artery disease.",
"<b>Diabetic cardiomyopathy:</b> myocardial dysfunction independent of coronary disease/hypertension, driven by lipotoxicity, myocardial fibrosis, mitochondrial dysfunction, and AGE cross-linking — manifests as diastolic dysfunction progressing to heart failure.",
"<b>Silent myocardial ischemia:</b> autonomic neuropathy blunts anginal pain perception → higher risk of unrecognized MI.",
"<b>Autonomic neuropathy:</b> resting tachycardia, orthostatic hypotension, reduced heart rate variability.",
"<b>Heart failure:</b> diabetics have 2–4x increased risk of heart failure (both HFrEF and HFpEF).",
"<b>Management:</b> aggressive risk factor control (statins, BP control), SGLT2 inhibitors (proven cardiovascular/heart failure benefit), GLP-1 receptor agonists (proven MACE reduction), antiplatelet therapy where indicated.",
]))
story.append(PageBreak())
story.append(section(9, "Non-Alcoholic Fatty Liver Disease (NAFLD) — Detailed"))
story.append(sub("Definition and Epidemiology"))
story.append(P("NAFLD is defined as hepatic steatosis (fat in >5% of hepatocytes) on imaging or biopsy in the absence of significant alcohol use or other secondary causes of fat accumulation. It is now the most common chronic liver disease worldwide and is present in up to 55-70% of people with type 2 diabetes, reflecting the shared driver of insulin resistance."))
story.append(sub("Pathophysiology"))
story.append(subsub("The 'Multiple-Hit' Model"))
story.append(bullets([
"<b>Insulin resistance</b> is central: it impairs suppression of adipose tissue lipolysis → increased free fatty acid (FFA) flux to the liver.",
"Hyperinsulinemia also directly stimulates hepatic <b>de novo lipogenesis</b> via SREBP-1c activation, and impairs fatty acid oxidation.",
"Excess FFAs accumulate as hepatic triglyceride (simple steatosis) — the 'first hit'.",
"<b>Lipotoxicity:</b> toxic lipid intermediates (diacylglycerol, ceramides, free cholesterol - not triglyceride itself) cause mitochondrial dysfunction, ER stress, and oxidative stress ('second hit').",
"This drives hepatocyte injury (ballooning), activation of Kupffer cells and hepatic stellate cells, and an inflammatory/fibrogenic response → progression from simple fatty liver to <b>steatohepatitis (NASH)</b>.",
"Gut-derived factors (dysbiosis, increased intestinal permeability/endotoxin) and genetic polymorphisms (e.g., PNPLA3, TM6SF2) modulate individual risk and rate of progression.",
]))
story.append(sub("Spectrum / Stages of Disease"))
story.append(make_table(
["Stage", "Features"],
[
["NAFL (simple steatosis)", "Hepatic fat accumulation without significant inflammation or hepatocyte injury; generally benign, slow progression"],
["NASH (non-alcoholic steatohepatitis)", "Steatosis + lobular inflammation + hepatocyte ballooning injury +/- Mallory-Denk bodies; can progress to fibrosis"],
["Fibrosis (F1-F4)", "Progressive peri-sinusoidal/portal fibrosis from NASH; F4 = cirrhosis"],
["Cirrhosis", "End-stage fibrosis with architectural distortion; risk of decompensation and portal hypertension"],
["Hepatocellular carcinoma (HCC)", "Can arise from NASH-cirrhosis, and occasionally from NASH without cirrhosis"],
],
col_widths=[5*cm, 11.5*cm]
))
story.append(sub("Risk Factors"))
story.append(bullets([
"Type 2 diabetes mellitus and insulin resistance (strongest associations).",
"Obesity, especially visceral/central adiposity.",
"Metabolic syndrome (dyslipidemia - especially high triglycerides/low HDL, hypertension).",
"Polycystic ovary syndrome, hypothyroidism, obstructive sleep apnea (associated conditions).",
]))
story.append(sub("Clinical Features"))
story.append(bullets([
"Usually asymptomatic; may have vague right upper quadrant discomfort or fatigue.",
"Hepatomegaly may be present on examination.",
"Signs of cirrhosis (spider angiomata, palmar erythema, ascites, jaundice) only in advanced disease.",
]))
story.append(sub("Diagnosis"))
story.append(bullets([
"<b>Liver enzymes:</b> mild elevation of ALT and AST, typically ALT > AST (reverses toward AST-predominant as fibrosis/cirrhosis develops); enzymes can also be entirely normal.",
"<b>Imaging:</b> ultrasound (hyperechoic 'bright liver', first-line, but insensitive for mild steatosis); CT/MRI more sensitive; <b>MRI-PDFF</b> is the most accurate non-invasive quantifier of fat.",
"<b>Non-invasive fibrosis scores:</b> FIB-4 index and NAFLD Fibrosis Score (NFS) using age, BMI, platelets, albumin, AST/ALT — used to risk-stratify and decide who needs specialist referral or biopsy.",
"<b>Transient elastography (FibroScan)</b> and MR elastography — assess liver stiffness as a surrogate for fibrosis.",
"<b>Liver biopsy</b> — gold standard; required to definitively diagnose NASH and stage fibrosis, but invasive; reserved for diagnostic uncertainty or when it will change management.",
]))
story.append(sub("Management"))
story.append(bullets([
"<b>Weight loss</b> — the cornerstone of treatment; 7-10% body weight loss improves steatosis, inflammation, and can regress fibrosis; >10% loss shown to induce NASH resolution in many patients.",
"<b>Glycemic control</b> — optimize diabetes management; poor glycemic control accelerates progression.",
"<b>Pioglitazone</b> — improves hepatic histology (steatosis and inflammation) in biopsy-proven NASH, including in diabetics; weight gain and fluid retention are trade-offs.",
"<b>GLP-1 receptor agonists</b> (liraglutide, semaglutide) — promote weight loss and have shown histological improvement in NASH trials.",
"<b>Vitamin E</b> — may be used in non-diabetic biopsy-proven NASH (antioxidant effect); use is more controversial in diabetics.",
"Avoid alcohol; manage dyslipidemia (statins are safe in NAFLD/NASH and do not need to be withheld); bariatric surgery can be considered in eligible obese patients and improves/resolves NASH in many.",
"Screen for and manage cardiovascular risk — cardiovascular disease, not liver disease, is the leading cause of death in NAFLD patients.",
"Surveillance for hepatocellular carcinoma and varices once cirrhosis develops.",
]))
story.append(PageBreak())
story.append(section(10, "Infant of a Diabetic Mother (IDM)"))
story.append(sub("Pathophysiology — The Pedersen Hypothesis"))
story.append(P("Maternal hyperglycemia crosses the placenta freely (glucose crosses; maternal insulin does not). This exposes the fetus to chronically elevated glucose → fetal pancreatic beta-cell hyperplasia → <b>fetal hyperinsulinemia</b>. Because insulin is a potent fetal growth factor, this single mechanism (fetal hyperinsulinemia) underlies almost all classic complications of IDM — both during pregnancy and after birth."))
story.append(sub("A. Complications to the Mother (during pregnancy)"))
story.append(bullets([
"<b>Pre-eclampsia / gestational hypertension</b> — 2-4x more common in diabetic pregnancies, especially with pre-existing vascular disease.",
"<b>Polyhydramnios</b> — fetal hyperglycemia causes fetal polyuria, increasing amniotic fluid volume; raises risk of preterm labor and malpresentation.",
"<b>Worsening of maternal diabetic retinopathy and nephropathy</b> — pregnancy can accelerate progression of existing microvascular disease.",
"<b>Diabetic ketoacidosis (DKA)</b> — pregnancy is a ketogenic state; DKA can occur at lower glucose thresholds than in non-pregnant patients and is dangerous for both mother and fetus.",
"<b>Increased infection risk</b> — urinary tract infections, candidiasis.",
"<b>Obstructed/prolonged labor and operative delivery</b> — due to fetal macrosomia; increased rates of Cesarean section.",
"<b>Postpartum hemorrhage</b> — from uterine overdistension (polyhydramnios/macrosomia) and prolonged labor.",
]))
story.append(sub("B. Complications to the Fetus (during pregnancy / at birth)"))
story.append(bullets([
"<b>Macrosomia</b> (birth weight >4 kg or >90th percentile) — fetal hyperinsulinemia drives excess growth of insulin-sensitive tissues (fat, muscle, organomegaly), sparing the brain — classic asymmetric growth with increased shoulder/trunk size predisposing to <b>shoulder dystocia</b> and birth trauma (brachial plexus injury, clavicle fracture).",
"<b>Congenital malformations</b> (2-4x general population risk) — related to poor glycemic control during organogenesis (first trimester, weeks 3-8): cardiac defects (VSD, transposition of the great vessels), neural tube defects, and the classic but rare <b>caudal regression syndrome (sacral agenesis)</b>.",
"<b>Intrauterine growth restriction (IUGR)</b> — can occur instead of macrosomia if the mother has advanced vascular disease (placental insufficiency).",
"<b>Unexplained stillbirth</b> — risk increased with poor glycemic control, especially in the third trimester.",
"<b>Fetal hypoxia</b> — chronic hyperglycemia increases fetal oxygen consumption and can cause relative intrauterine hypoxia, stimulating erythropoietin and polycythemia.",
]))
story.append(sub("C. Treatment / Management of the Mother During Pregnancy"))
story.append(bullets([
"<b>Preconception counseling</b> — optimize HbA1c (target <6.5% ideally) before conception to reduce malformation risk; start high-dose folic acid.",
"<b>Glycemic targets in pregnancy</b> — tighter than usual: fasting <95 mg/dL, 1-hr postprandial <140 mg/dL, 2-hr postprandial <120 mg/dL.",
"<b>Insulin is the preferred pharmacologic agent in pregnancy</b> (does not cross the placenta in clinically significant amounts); doses typically need to increase progressively through pregnancy due to rising insulin resistance from placental hormones (human placental lactogen, cortisol, progesterone).",
"Metformin and glyburide are sometimes used (particularly in gestational diabetes) but insulin remains first-line/preferred, especially in pre-existing diabetes.",
"<b>Self-monitoring of blood glucose</b> multiple times daily; regular HbA1c monitoring.",
"<b>Ophthalmologic exam</b> each trimester (risk of retinopathy progression); renal function monitoring.",
"<b>Nutrition/dietary counseling</b> and regular physical activity as tolerated.",
"Low-dose aspirin from the end of the first trimester to reduce pre-eclampsia risk (standard for pregestational diabetes).",
]))
story.append(sub("D. Monitoring / Treatment of the Fetus During Pregnancy"))
story.append(bullets([
"<b>Serial growth ultrasounds</b> — monitor for macrosomia or growth restriction, and amniotic fluid volume (polyhydramnios).",
"<b>Fetal echocardiography</b> — offered given increased risk of congenital heart defects.",
"<b>Antenatal fetal surveillance</b> in the third trimester — non-stress tests (NST), biophysical profile, umbilical artery Doppler if growth-restricted.",
"<b>Timing of delivery</b> — individualized; often delivery is planned around 39-40 weeks (earlier if poor control, macrosomia, or other complications) to balance risks of stillbirth against prematurity.",
"Consideration of elective Cesarean section if estimated fetal weight is very high, to reduce shoulder dystocia risk.",
]))
story.append(sub("E. Management of the Baby After Birth (Neonatal Period)"))
story.append(bullets([
"<b>Neonatal hypoglycemia</b> — the most important immediate risk: after cord clamping, the maternal glucose supply stops abruptly but fetal hyperinsulinemia persists for hours to days → profound hypoglycemia. Manage with early feeding within the first hour, frequent bedside glucose monitoring (per protocol, e.g., at 30 min, 1, 2, 4, 6, 12, 24 hours), and IV dextrose if symptomatic or glucose remains low despite feeding.",
"<b>Respiratory distress syndrome (RDS)</b> — fetal hyperinsulinemia antagonizes cortisol's stimulation of surfactant production, delaying lung maturity even at term; monitor respiratory status closely and support as needed (may require surfactant/NICU care).",
"<b>Hypertrophic cardiomyopathy</b> — transient septal/ventricular wall thickening from hyperinsulinemia; usually resolves over weeks to months; echocardiogram if murmur or respiratory/feeding difficulty.",
"<b>Polycythemia</b> — from chronic relative intrauterine hypoxia driving erythropoietin; monitor hematocrit; partial exchange transfusion rarely needed for severe symptomatic cases.",
"<b>Hyperbilirubinemia/jaundice</b> — from breakdown of excess red cells (polycythemia) and immature hepatic conjugation; monitor bilirubin, treat with phototherapy as needed.",
"<b>Hypocalcemia and hypomagnesemia</b> — due to delayed parathyroid hormone response; monitor calcium/magnesium, supplement if symptomatic (jitteriness, seizures).",
"<b>Birth injury</b> from macrosomia/shoulder dystocia — examine for brachial plexus injury (Erb's palsy), clavicle fracture, cephalohematoma.",
"<b>Screen for congenital anomalies</b> if not already characterized antenatally (cardiac exam/echo, spine exam).",
"Longer-term: IDM babies have increased lifetime risk of obesity, impaired glucose tolerance, and type 2 diabetes themselves — anticipatory guidance for the family."
]))
story.append(Spacer(1, 20))
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#B0B0B0")))
story.append(Spacer(1, 6))
story.append(Paragraph(
"<i>This study guide is compiled from standard medical education content for exam preparation purposes. "
"Always verify current clinical guidelines and drug dosing against up-to-date primary sources before clinical application.</i>",
styles["Body"]
))
def add_page_number(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.setFillColor(colors.grey)
canvas.drawCentredString(A4[0] / 2, 1.2 * cm, f"Page {doc.page} | Diabetes Mellitus Study Guide")
canvas.restoreState()
doc = SimpleDocTemplate(
OUT, pagesize=A4,
topMargin=1.8*cm, bottomMargin=1.8*cm, leftMargin=1.8*cm, rightMargin=1.8*cm,
title="Diabetes Mellitus Study Guide"
)
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
print("PDF written to", OUT)
| Pathway | Effect of Insulin |
|---|---|
| Glycolysis | Stimulates (via hexokinase, PFK-1, pyruvate kinase induction) |
| Glycogenesis | Stimulates (activates glycogen synthase) |
| Glycogenolysis | Inhibits |
| Gluconeogenesis | Inhibits (suppresses PEPCK, fructose-1,6-bisphosphatase, glucose-6-phosphatase) |
| Lipogenesis | Stimulates (activates acetyl-CoA carboxylase, fatty acid synthase) |
| Lipolysis | Inhibits (inhibits hormone-sensitive lipase) |
| Proteolysis | Inhibits; promotes protein synthesis |
| Test | Normal | Prediabetes | Diabetes |
|---|---|---|---|
| Fasting Plasma Glucose (FPG) | <100 mg/dL (5.6 mmol/L) | 100-125 mg/dL | ≥126 mg/dL (7.0 mmol/L) |
| 2-hr OGTT (75g glucose load) | <140 mg/dL | 140-199 mg/dL | ≥200 mg/dL (11.1 mmol/L) |
| HbA1c | <5.7% | 5.7-6.4% | ≥6.5% |
| Random Plasma Glucose + symptoms | - | - | ≥200 mg/dL |
| Class | Examples | Mechanism/Receptor Target | Key Side Effects |
|---|---|---|---|
| Biguanides | Metformin | Activates AMPK; decreases hepatic gluconeogenesis, increases peripheral insulin sensitivity | GI upset, lactic acidosis (rare), B12 deficiency |
| Sulfonylureas | Glibenclamide, Glipizide, Glimepiride | Bind SUR1 subunit of KATP channel on beta cells → closes channel → insulin release | Hypoglycemia, weight gain |
| Meglitinides | Repaglinide, Nateglinide | Same KATP/SUR1 site, faster/shorter action | Hypoglycemia (less than SU) |
| Thiazolidinediones (TZDs) | Pioglitazone, Rosiglitazone | Activate PPAR-gamma nuclear receptor → improves insulin sensitivity in adipose/muscle | Weight gain, fluid retention, heart failure risk, fracture risk |
| Alpha-glucosidase inhibitors | Acarbose, Miglitol | Inhibit intestinal alpha-glucosidase → delay carbohydrate absorption | Flatulence, GI upset |
| DPP-4 inhibitors (gliptins) | Sitagliptin, Vildagliptin, Linagliptin | Inhibit dipeptidyl peptidase-4 → increases endogenous GLP-1/GIP levels | Generally well tolerated; pancreatitis risk (rare) |
| GLP-1 receptor agonists | Exenatide, Liraglutide, Semaglutide, Dulaglutide | Agonists at GLP-1 receptor → glucose-dependent insulin secretion, decreases glucagon, delays gastric emptying, satiety | Nausea, vomiting, pancreatitis risk |
| SGLT2 inhibitors | Empagliflozin, Dapagliflozin, Canagliflozin | Inhibit sodium-glucose cotransporter 2 in proximal renal tubule → glucosuria | UTI, genital mycotic infections, euglycemic DKA |
| Amylin analogs | Pramlintide | Mimics amylin, co-secreted with insulin - slows gastric emptying, suppresses glucagon | Nausea, hypoglycemia (with insulin) |
| Insulin | (see section 4) | Insulin receptor (tyrosine kinase) | Hypoglycemia, weight gain |
| Type | Examples | Onset | Peak | Duration |
|---|---|---|---|---|
| Rapid-acting | Lispro, Aspart, Glulisine | 10-15 min | 1-2 hr | 3-5 hr |
| Short-acting (Regular) | Regular human insulin | 30-60 min | 2-3 hr | 5-8 hr |
| Intermediate-acting | NPH (isophane) | 2-4 hr | 4-10 hr | 10-16 hr |
| Long-acting | Glargine, Detemir | 1-2 hr | minimal peak | 20-24 hr |
| Ultra-long-acting | Degludec | 30-90 min | minimal peak | up to 42 hr |
| Premixed | 70/30 NPH/Regular, 75/25 lispro protamine/lispro | Combination profile | Combination | Combination |
Diabetes Mellitus Study Guide
PDF Document · PDF
Diabetes Mellitus Study Guide
PDF Document · PDF
An error occurred (ValidationException) when calling the InvokeCodeInterpreter operation: Code interpreter session 01M0JPA9MP4SVFABG5DNVNC4DR is not active
We encountered an error while processing your request. Please try again or reach out to us for help.
An error occurred (ValidationException) when calling the InvokeCodeInterpreter operation: Code interpreter session 01M0JPA9MP4SVFABG5DNVNC4DR is not active
We encountered an error while processing your request. Please try again or reach out to us for help.
Relax baby its all ok
ls -la /tmp/workspace/diabetes-study-guide/ /tmp/workspace/diabetes-study-guide/images/ 2>/dev/null
cd /tmp/workspace/diabetes-study-guide && python3 -c " from pypdf import PdfReader r = PdfReader('Diabetes_Mellitus_Study_Guide.pdf') print('Pages:', len(r.pages)) print('Title:', r.metadata.title) "