Write me a shrot notes for the following topics from anil k tripathi book of general medicine for bds gujarat university for 3 year exams about 7-8 marks Male concise to the point precise ans to the topics are Syncope Arrhythmia Pneumonia Lung abscess Bronchial asthma In pdf form

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

mkdir -p /tmp/workspace/bds-notes && python3 << 'EOF' from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import cm from reportlab.lib import colors from reportlab.platypus import ( SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, PageBreak, KeepTogether ) from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY doc = SimpleDocTemplate( "/tmp/workspace/bds-notes/General_Medicine_Short_Notes_BDS.pdf", pagesize=A4, leftMargin=2*cm, rightMargin=2*cm, topMargin=2*cm, bottomMargin=2*cm ) styles = getSampleStyleSheet() # Custom styles title_style = ParagraphStyle( 'MainTitle', parent=styles['Title'], fontSize=18, textColor=colors.HexColor('#1a237e'), spaceAfter=4, alignment=TA_CENTER, fontName='Helvetica-Bold' ) subtitle_style = ParagraphStyle( 'SubTitle', parent=styles['Normal'], fontSize=10, textColor=colors.HexColor('#4a4a4a'), spaceAfter=12, alignment=TA_CENTER, fontName='Helvetica-Oblique' ) topic_heading = ParagraphStyle( 'TopicHeading', parent=styles['Heading1'], fontSize=14, textColor=colors.white, spaceAfter=0, spaceBefore=6, backColor=colors.HexColor('#1a237e'), fontName='Helvetica-Bold', leftIndent=-0.5*cm, rightIndent=-0.5*cm, borderPad=6 ) section_heading = ParagraphStyle( 'SectionHeading', parent=styles['Heading2'], fontSize=11, textColor=colors.HexColor('#1a237e'), spaceAfter=2, spaceBefore=6, fontName='Helvetica-Bold', borderPad=2 ) body_style = ParagraphStyle( 'Body', parent=styles['Normal'], fontSize=9.5, textColor=colors.HexColor('#212121'), spaceAfter=3, spaceBefore=1, leading=14, alignment=TA_JUSTIFY, fontName='Helvetica' ) bullet_style = ParagraphStyle( 'Bullet', parent=styles['Normal'], fontSize=9.5, textColor=colors.HexColor('#212121'), spaceAfter=2, spaceBefore=1, leading=13, leftIndent=14, bulletIndent=4, fontName='Helvetica' ) sub_bullet_style = ParagraphStyle( 'SubBullet', parent=styles['Normal'], fontSize=9.5, textColor=colors.HexColor('#212121'), spaceAfter=2, spaceBefore=1, leading=13, leftIndent=28, bulletIndent=18, fontName='Helvetica' ) bold_label = ParagraphStyle( 'BoldLabel', parent=styles['Normal'], fontSize=9.5, textColor=colors.HexColor('#1a237e'), spaceAfter=1, spaceBefore=3, fontName='Helvetica-Bold' ) footer_style = ParagraphStyle( 'Footer', parent=styles['Normal'], fontSize=8, textColor=colors.HexColor('#757575'), alignment=TA_CENTER ) def topic_banner(title, number): data = [[Paragraph(f"TOPIC {number}: {title}", ParagraphStyle( 'banner', fontSize=13, textColor=colors.white, fontName='Helvetica-Bold', alignment=TA_LEFT ))]] t = Table(data, colWidths=[17*cm]) t.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#1a237e')), ('TOPPADDING', (0,0), (-1,-1), 8), ('BOTTOMPADDING', (0,0), (-1,-1), 8), ('LEFTPADDING', (0,0), (-1,-1), 10), ])) return t def section_box(title): data = [[Paragraph(title, ParagraphStyle( 'sbox', fontSize=10, textColor=colors.HexColor('#1a237e'), fontName='Helvetica-Bold' ))]] t = Table(data, colWidths=[17*cm]) t.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#e8eaf6')), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 8), ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor('#3949ab')), ])) return t def b(text): return f"<b>{text}</b>" def i(text): return f"<i>{text}</i>" story = [] # ============================================================ # HEADER # ============================================================ story.append(Spacer(1, 0.3*cm)) story.append(Paragraph("GENERAL MEDICINE", title_style)) story.append(Paragraph("Short Notes for BDS 3rd Year | Gujarat University Examinations", subtitle_style)) story.append(Paragraph("Based on Anil K. Tripathi — General Medicine for BDS", ParagraphStyle( 'ref', fontSize=9, textColor=colors.HexColor('#757575'), alignment=TA_CENTER, fontName='Helvetica-Oblique', spaceAfter=4 ))) story.append(Paragraph("Each topic: 7-8 Marks | Concise, Precise, Exam-Oriented", ParagraphStyle( 'info', fontSize=9, textColor=colors.HexColor('#e53935'), alignment=TA_CENTER, fontName='Helvetica-Bold', spaceAfter=10 ))) story.append(HRFlowable(width="100%", thickness=2, color=colors.HexColor('#1a237e'))) story.append(Spacer(1, 0.3*cm)) # Table of Contents toc_data = [ [Paragraph(b("No."), body_style), Paragraph(b("Topic"), body_style), Paragraph(b("Marks"), body_style)], [Paragraph("1.", body_style), Paragraph("Syncope", body_style), Paragraph("7-8", body_style)], [Paragraph("2.", body_style), Paragraph("Arrhythmia", body_style), Paragraph("7-8", body_style)], [Paragraph("3.", body_style), Paragraph("Pneumonia", body_style), Paragraph("7-8", body_style)], [Paragraph("4.", body_style), Paragraph("Lung Abscess", body_style), Paragraph("7-8", body_style)], [Paragraph("5.", body_style), Paragraph("Bronchial Asthma", body_style), Paragraph("7-8", body_style)], ] toc_table = Table(toc_data, colWidths=[1.5*cm, 13*cm, 2.5*cm]) toc_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('ALIGN', (2,0), (2,-1), 'CENTER'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 8), ])) story.append(toc_table) story.append(Spacer(1, 0.5*cm)) story.append(PageBreak()) # ============================================================ # TOPIC 1: SYNCOPE # ============================================================ story.append(topic_banner("SYNCOPE", "1")) story.append(Spacer(1, 0.2*cm)) story.append(section_box("Definition")) story.append(Paragraph( "Syncope is a transient, self-limited loss of consciousness (TLOC) due to global cerebral hypoperfusion, " "characterized by a rapid onset, short duration, and spontaneous complete recovery, without neurological deficit.", body_style)) story.append(Spacer(1, 0.1*cm)) story.append(section_box("Etiology / Classification")) etiology_data = [ [Paragraph(b("Type"), body_style), Paragraph(b("Causes"), body_style)], [Paragraph("Vasovagal (Neurocardiogenic)", body_style), Paragraph("Most common. Triggered by emotional stress, pain, prolonged standing, sight of blood. " "Due to paradoxical bradycardia + hypotension.", body_style)], [Paragraph("Cardiac", body_style), Paragraph("Arrhythmias (VT, VF, sick sinus syndrome, complete heart block), aortic stenosis, " "HOCM, massive MI, cardiac tamponade.", body_style)], [Paragraph("Orthostatic Hypotension", body_style), Paragraph("Drop in SBP >20 mmHg on standing. Causes: dehydration, drugs (antihypertensives, diuretics), " "autonomic neuropathy (diabetes), Addison's disease.", body_style)], [Paragraph("Situational", body_style), Paragraph("Micturition syncope, cough syncope, swallowing syncope, defecation syncope.", body_style)], [Paragraph("Carotid Sinus", body_style), Paragraph("Hypersensitive carotid sinus reflex; provoked by neck turning, tight collar.", body_style)], [Paragraph("Neurological", body_style), Paragraph("Vertebrobasilar TIA, subclavian steal syndrome (rare causes).", body_style)], ] etio_table = Table(etiology_data, colWidths=[5*cm, 12*cm]) etio_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(etio_table) story.append(Spacer(1, 0.15*cm)) story.append(section_box("Clinical Features")) story.append(Paragraph(b("Pre-syncopal Prodrome (Warning symptoms):"), bold_label)) for item in [ "Dizziness, lightheadedness, nausea, sweating", "Blurring / greying out of vision, ringing in ears", "Pallor, weakness — lasts seconds to minutes", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("During syncope:"), bold_label)) for item in [ "Sudden loss of consciousness and postural tone", "Patient falls — may sustain injury", "Brief tonic-clonic jerks possible (not a true seizure) if ischemia is prolonged", "Pallor, slow weak pulse, dilated pupils", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Post-syncopal:"), bold_label)) for item in [ "Rapid spontaneous recovery on becoming supine (within seconds)", "No post-ictal confusion (differentiates from seizure)", "Mild fatigue or headache may persist", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Diagnosis")) for item in [ b("History") + " — detailed history of trigger, prodrome, duration, recovery is the most important diagnostic tool", b("ECG") — detect arrhythmias, heart block, QT prolongation, Brugada syndrome", b("Holter Monitor / Event Recorder") — for paroxysmal arrhythmias; implantable loop recorder for recurrent unexplained syncope", b("Echocardiography") — for structural heart disease (aortic stenosis, HOCM)", b("Tilt Table Test") — for suspected vasovagal/orthostatic syncope", b("Carotid Sinus Massage") — for carotid sinus hypersensitivity (only in monitored setting)", b("Blood Tests") — CBC, blood glucose, electrolytes to exclude metabolic causes", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Treatment")) story.append(Paragraph(b("General / Vasovagal:"), bold_label)) for item in [ "Place patient supine, elevate legs to restore cerebral perfusion", "Patient education: avoid triggers, dehydration", "Physical counter-pressure maneuvers (leg crossing, hand gripping)", "Increased salt and fluid intake", "Beta-blockers (atenolol) — in selected cases; midodrine for orthostatic type", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Cardiac Syncope:"), bold_label)) for item in [ "Treat underlying arrhythmia — pacemaker for bradyarrhythmias", "ICD (implantable cardioverter-defibrillator) for VT/VF", "Surgery for structural lesions (aortic stenosis, HOCM)", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Dental Relevance:"), bold_label)) story.append(Paragraph( "Vasovagal syncope is the most common emergency in dental practice. " "Prevention: treat anxious patients in supine/semi-reclined position, adequate analgesia, " "minimize waiting time. Management: lay patient flat, elevate legs, loosen tight clothing, " "ensure airway. Atropine 0.6 mg IV if persistent bradycardia.", body_style)) story.append(PageBreak()) # ============================================================ # TOPIC 2: ARRHYTHMIA # ============================================================ story.append(topic_banner("ARRHYTHMIA", "2")) story.append(Spacer(1, 0.2*cm)) story.append(section_box("Definition")) story.append(Paragraph( "Arrhythmia (or dysrhythmia) is any disturbance in the normal rate, rhythm, site of origin, or conduction " "of the cardiac electrical impulse. The normal sinus rhythm has a rate of 60-100 bpm, with P wave " "preceding every QRS complex.", body_style)) story.append(section_box("Classification")) class_data = [ [Paragraph(b("Category"), body_style), Paragraph(b("Types"), body_style)], [Paragraph("By Rate", body_style), Paragraph("Bradyarrhythmia (<60 bpm) | Tachyarrhythmia (>100 bpm)", body_style)], [Paragraph("Supraventricular\n(above Bundle of His)", body_style), Paragraph("Sinus tachycardia, Sinus bradycardia, SVT, AF, Atrial flutter, " "AVNRT, WPW syndrome, Junctional rhythm", body_style)], [Paragraph("Ventricular", body_style), Paragraph("PVCs, Ventricular tachycardia (VT), Ventricular fibrillation (VF), " "Torsades de pointes, Accelerated idioventricular rhythm", body_style)], [Paragraph("Conduction Defects", body_style), Paragraph("1st, 2nd (Mobitz I & II), 3rd degree AV block; Bundle branch blocks (LBBB, RBBB); " "Sick sinus syndrome", body_style)], ] class_table = Table(class_data, colWidths=[5*cm, 12*cm]) class_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(class_table) story.append(Spacer(1, 0.15*cm)) story.append(section_box("Common Arrhythmias — Key Features")) story.append(Paragraph(b("1. Atrial Fibrillation (AF)"), bold_label)) for item in [ "Most common sustained cardiac arrhythmia", "Chaotic, irregular atrial activity at 350-600 impulses/min", b("ECG") + ": absent P waves, irregularly irregular QRS, fibrillatory baseline", b("Causes") + ": hypertension, rheumatic heart disease, thyrotoxicosis, ischemic heart disease, alcohol", b("Risks") + ": embolic stroke (thrombus in LAA), heart failure", b("Treatment") + ": Rate control (beta-blockers, digoxin, CCBs) | Rhythm control (cardioversion, amiodarone) | Anticoagulation (warfarin/NOAC) to prevent stroke", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("2. Ventricular Tachycardia (VT)"), bold_label)) for item in [ "3 or more consecutive ventricular beats at rate >100 bpm", b("ECG") + ": wide QRS (>0.12s), AV dissociation, fusion beats", b("Causes") + ": MI, cardiomyopathy, electrolyte disturbances", b("Treatment") + ": Stable VT — IV amiodarone/lignocaine; Unstable VT — DC cardioversion; ICD for recurrent VT", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("3. Complete Heart Block (3rd Degree AV Block)"), bold_label)) for item in [ "Complete dissociation between atrial and ventricular activity", b("ECG") + ": P waves and QRS complexes independent, slow ventricular escape rhythm (20-40 bpm)", b("Symptoms") + ": Stokes-Adams attacks (sudden LOC), heart failure, bradycardia", b("Treatment") + ": Permanent pacemaker", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("4. Sick Sinus Syndrome"), bold_label)) for item in [ "Dysfunction of SA node causing bradycardia, SA block, sinus arrest", "May alternate with tachyarrhythmias (brady-tachy syndrome)", b("Treatment") + ": Pacemaker implantation", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Diagnosis")) for item in [ b("ECG (12-lead)") + " — single most important investigation", b("Holter Monitor") + " — 24-48 hour ambulatory ECG", b("Electrophysiological study (EPS)") + " — for complex arrhythmias", b("Echocardiography") + " — assess structural heart disease", b("Blood tests") + " — electrolytes (K+, Mg2+), TFTs, cardiac enzymes", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("General Principles of Treatment")) treat_data = [ [Paragraph(b("Approach"), body_style), Paragraph(b("Details"), body_style)], [Paragraph("Rate Control", body_style), Paragraph("Beta-blockers, CCBs (verapamil, diltiazem), digoxin", body_style)], [Paragraph("Rhythm Control", body_style), Paragraph("Antiarrhythmics: amiodarone, flecainide, sotalol; DC cardioversion", body_style)], [Paragraph("Pacemakers", body_style), Paragraph("Bradyarrhythmias, complete heart block, sick sinus syndrome", body_style)], [Paragraph("ICD", body_style), Paragraph("VT/VF, high-risk patients with structural heart disease", body_style)], [Paragraph("Ablation", body_style), Paragraph("SVT, WPW, AF — radiofrequency catheter ablation", body_style)], [Paragraph("Anticoagulation", body_style), Paragraph("AF — warfarin or NOACs (rivaroxaban, apixaban)", body_style)], ] treat_table = Table(treat_data, colWidths=[4*cm, 13*cm]) treat_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(treat_table) story.append(Paragraph(b("Dental Relevance:"), bold_label)) story.append(Paragraph( "Patients on anticoagulants (warfarin) need INR check before extraction (target <3.5 for minor surgery). " "Avoid epinephrine-containing LA in patients with severe arrhythmias or on digoxin. " "Cardiac monitoring is advisable for high-risk patients. Erythromycin, clarithromycin can prolong QT interval — " "use cautiously in arrhythmia patients.", body_style)) story.append(PageBreak()) # ============================================================ # TOPIC 3: PNEUMONIA # ============================================================ story.append(topic_banner("PNEUMONIA", "3")) story.append(Spacer(1, 0.2*cm)) story.append(section_box("Definition")) story.append(Paragraph( "Pneumonia is an acute inflammatory condition of the lung parenchyma (alveoli, alveolar ducts, and respiratory bronchioles) " "caused by microbial infection, resulting in consolidation and impaired gas exchange.", body_style)) story.append(section_box("Classification")) class2_data = [ [Paragraph(b("By Setting"), body_style), Paragraph(b("By Etiology"), body_style), Paragraph(b("By Anatomy"), body_style)], [Paragraph("• Community-Acquired (CAP)\n• Hospital-Acquired (HAP) — >48h after admission\n• Ventilator-Associated (VAP)\n• Aspiration Pneumonia\n• Immunocompromised Host Pneumonia", body_style), Paragraph("• Bacterial: S. pneumoniae (most common), Staphylococcus, Klebsiella, Legionella, Mycoplasma, H. influenzae\n• Viral: Influenza, COVID-19, RSV\n• Fungal: Pneumocystis jirovecii (immunocompromised)\n• Atypical: Mycoplasma, Chlamydia, Legionella", body_style), Paragraph("• Lobar pneumonia — entire lobe\n• Bronchopneumonia — patchy, multifocal\n• Interstitial pneumonia — alveolar walls", body_style)], ] class2_table = Table(class2_data, colWidths=[5.5*cm, 7.5*cm, 4*cm]) class2_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ])) story.append(class2_table) story.append(Spacer(1, 0.15*cm)) story.append(section_box("Pathology — Lobar Pneumonia (4 Stages)")) path_data = [ [Paragraph(b("Stage"), body_style), Paragraph(b("Duration"), body_style), Paragraph(b("Features"), body_style)], [Paragraph("1. Congestion", body_style), Paragraph("1-2 days", body_style), Paragraph("Vascular engorgement, edema fluid, few bacteria", body_style)], [Paragraph("2. Red Hepatization", body_style), Paragraph("2-4 days", body_style), Paragraph("Lobe firm like liver; alveoli filled with RBCs, fibrin, PMNs", body_style)], [Paragraph("3. Grey Hepatization", body_style), Paragraph("4-8 days", body_style), Paragraph("RBCs lysed; alveoli filled with fibrin, PMNs, macrophages", body_style)], [Paragraph("4. Resolution", body_style), Paragraph("8-9 days", body_style), Paragraph("Enzymatic digestion of exudate; normal lung architecture restored", body_style)], ] path_table = Table(path_data, colWidths=[4.5*cm, 2.5*cm, 10*cm]) path_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(path_table) story.append(Spacer(1, 0.15*cm)) story.append(section_box("Clinical Features")) story.append(Paragraph(b("Symptoms:"), bold_label)) for item in [ b("Sudden onset") + " high-grade fever (39-40°C) with rigors/chills", b("Productive cough") + " — rusty/blood-tinged sputum (characteristic of pneumococcal pneumonia)", b("Pleuritic chest pain") + " — sharp, worse on inspiration", "Breathlessness, tachypnoea", "Herpes labialis (cold sores) may appear on lips", "Malaise, anorexia, headache", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Signs:"), bold_label)) for item in [ "Fever, tachycardia, tachypnoea, hypoxia", b("Inspection") + ": reduced chest expansion on affected side", b("Palpation") + ": increased vocal fremitus over consolidation", b("Percussion") + ": dull note over consolidated lobe", b("Auscultation") + ": bronchial breathing, increased vocal resonance, crepitations (crackles)", "Pleural friction rub in pleurisy", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Investigations")) for item in [ b("Chest X-ray") + " — consolidation (homogeneous opacity), air bronchogram sign; most important investigation", b("Sputum Gram stain & culture") + " — identify organism and sensitivity", b("CBC") + " — neutrophilic leukocytosis (bacterial); lymphocytosis (viral)", b("Blood culture") + " — bacteremia in severe cases", b("ABG") + " — assess hypoxemia", b("Urine antigen tests") + " — for Legionella and pneumococcus", b("Serology") + " — for atypical pathogens (Mycoplasma, Chlamydia)", b("Pulse oximetry") + " — SpO2 monitoring", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Treatment")) story.append(Paragraph(b("Severity Assessment — CURB-65 Score:"), bold_label)) story.append(Paragraph( "C=Confusion | U=Urea >7 mmol/L | R=RR ≥30/min | B=BP systolic <90 or diastolic ≤60 | 65=age ≥65 years. " "Score 0-1: home treatment; Score 2: hospital; Score ≥3: ICU consideration.", body_style)) story.append(Paragraph(b("Antibiotics (CAP):"), bold_label)) for item in [ b("Mild/Outpatient") + ": Amoxicillin 500mg TDS x 5-7 days; or Doxycycline/Macrolide for atypicals", b("Moderate/Hospital") + ": IV Co-amoxiclav + Clarithromycin", b("Severe/ICU") + ": IV Piperacillin-tazobactam + Azithromycin/Levofloxacin", b("Aspiration pneumonia") + ": Metronidazole + Amoxicillin-clavulanate (anaerobic coverage)", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Supportive:"), bold_label)) for item in [ "Oxygen supplementation (target SpO2 >94%)", "IV fluids, antipyretics, analgesics", "Physiotherapy, postural drainage", "Ventilatory support if severe respiratory failure", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Complications:"), bold_label)) for item in [ "Pleural effusion / Empyema", "Lung abscess", "Respiratory failure (ARDS)", "Septicemia, septic shock", "Hepatitis (in atypical pneumonia)", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Dental Relevance:"), bold_label)) story.append(Paragraph( "Aspiration pneumonia can result from dental procedures — particularly in patients with impaired gag reflex, " "general anesthesia, or sedation. Oral pathogens (anaerobes from periodontal disease) are common culprits. " "Good oral hygiene reduces aspiration pneumonia risk in hospitalized/elderly patients.", body_style)) story.append(PageBreak()) # ============================================================ # TOPIC 4: LUNG ABSCESS # ============================================================ story.append(topic_banner("LUNG ABSCESS", "4")) story.append(Spacer(1, 0.2*cm)) story.append(section_box("Definition")) story.append(Paragraph( "Lung abscess is a localized area of suppuration (pus formation) within the pulmonary parenchyma, " "leading to necrosis and formation of one or more cavities (usually >2 cm) containing purulent material. " "It may be " + b("primary") + " (no pre-existing disease) or " + b("secondary") + " (complication of existing disease).", body_style)) story.append(section_box("Etiology / Predisposing Factors")) story.append(Paragraph(b("Organisms:"), bold_label)) for item in [ b("Anaerobes") + " (most common) — Bacteroides, Fusobacterium, Peptostreptococcus, Prevotella (oral flora)", b("Aerobes") + " — Staphylococcus aureus, Klebsiella pneumoniae, Pseudomonas, Streptococcus pyogenes", b("Mixed organisms") + " — anaerobes present in almost all cases", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Pathways of Infection:"), bold_label)) for item in [ b("Aspiration") + " (most common) — of infected material from carious teeth, infected gums, sinuses, tonsils; " "occurs in: unconsciousness, GA, alcohol intoxication, dysphagia, epilepsy", b("Complication of pneumonia") + " — necrotizing pneumonia (S. aureus, Klebsiella, anaerobes)", b("Bronchial obstruction") + " — carcinoma, foreign body causing distal infection", b("Hematogenous spread") + " — septic emboli from infective endocarditis, IV drug abuse → multiple abscesses", b("Traumatic") + " — penetrating chest injury", b("Subphrenic abscess") + " — direct spread through diaphragm", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Site of Predilection")) story.append(Paragraph( "Aspiration abscesses are more common in the " + b("right lung") + " (more vertical right main bronchus). " "In the " + b("recumbent position") + ": posterior segment of right upper lobe and apical segment of right lower lobe. " "In the " + b("upright position") + ": basal segments of lower lobes.", body_style)) story.append(section_box("Pathology")) for item in [ "Initial stage: area of pneumonia/consolidation → necrosis → liquefaction", "Central necrosis forms a cavity filled with pus and necrotic debris", "Cavity may communicate with bronchus → rupture → foul-smelling sputum expectorated", "Cavity wall: inner layer of necrotic tissue, outer layer of fibrous wall (chronic abscess)", "Abscess may rupture into pleural space → empyema or pyopneumothorax", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Clinical Features")) story.append(Paragraph(b("Acute Stage (1-2 weeks before cavity rupture into bronchus):"), bold_label)) for item in [ "High-grade fever with rigors, profuse sweating", "Pleuritic chest pain, breathlessness", "Dry cough, toxemia, malaise, weight loss", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("After Bronchial Communication (Drainage Phase):"), bold_label)) for item in [ b("Hallmark") + ": sudden expectoration of large amounts of " + b("foul-smelling, purulent sputum") + " (cupful in 24h)", "Blood-stained sputum (hemoptysis)", "Sputum settles in 3 layers: frothy top, watery middle, purulent/necrotic bottom (characteristic)", "Improvement in fever after drainage", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Signs:"), bold_label)) for item in [ "Clubbing of fingers (in chronic cases)", "Dullness to percussion over abscess", "Amphoric/cavernous breathing", "Coarse crepitations", "Signs of consolidation (if surrounding pneumonitis present)", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Investigations")) for item in [ b("Chest X-ray") + " — thick-walled cavity with air-fluid level (most characteristic finding); right-sided, single in aspiration", b("CT chest") + " — better delineation; distinguishes from empyema, tumor with central necrosis", b("Sputum culture") + " — Gram stain, culture & sensitivity (anaerobic culture important)", b("Bronchoscopy") + " — to exclude underlying carcinoma or foreign body; obtain specimens", b("CBC") + " — neutrophilic leukocytosis, raised ESR", b("Blood culture") + " — in hematogenous/septic cases", b("PFTs") + " — assess functional impairment", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Treatment")) story.append(Paragraph(b("Medical (First Line — Most Abscesses Respond):"), bold_label)) for item in [ b("Antibiotics") + ": IV Amoxicillin-clavulanate (co-amoxiclav) + Metronidazole (for anaerobes); " "or IV Clindamycin (drug of choice for aspiration/anaerobic lung abscess)", "Duration: usually " + b("6-8 weeks") + " to ensure complete resolution", b("Postural drainage + physiotherapy") + " — position patient with abscess uppermost to promote drainage", "Adequate nutrition and hydration", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Surgical (for failed medical therapy):"), bold_label)) for item in [ b("Percutaneous drainage") + " — CT-guided catheter drainage for large peripheral abscesses", b("Bronchoscopic drainage") + " — if endobronchial obstruction", b("Lobectomy/Pneumonectomy") + " — for large, chronic, non-resolving abscess or underlying malignancy", b("Indications for surgery") + ": no response after 6 weeks, abscess >6 cm, massive hemoptysis, underlying malignancy", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Complications:"), bold_label)) for item in [ "Empyema, pyopneumothorax", "Massive hemoptysis", "Septicemia, metastatic abscess (brain abscess)", "Bronchiectasis", "Respiratory failure", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Dental Relevance:"), bold_label)) story.append(Paragraph( "Poor oral hygiene, dental sepsis, and periodontal disease are the most important predisposing factors " "for aspiration lung abscess. Dental procedures under GA carry risk. " "Oral anaerobes (Bacteroides, Fusobacterium, Peptostreptococcus) are the main organisms. " "Therefore, thorough pre-operative oral hygiene and antibiotic prophylaxis reduce risk.", body_style)) story.append(PageBreak()) # ============================================================ # TOPIC 5: BRONCHIAL ASTHMA # ============================================================ story.append(topic_banner("BRONCHIAL ASTHMA", "5")) story.append(Spacer(1, 0.2*cm)) story.append(section_box("Definition")) story.append(Paragraph( "Bronchial asthma is a chronic inflammatory disease of the airways characterized by: " "(1) " + b("Airway hyperresponsiveness") + " to various stimuli, " "(2) " + b("Reversible airflow obstruction") + " (spontaneously or with treatment), and " "(3) " + b("Airway inflammation") + " with mucosal edema, mucus hypersecretion, and bronchoconstriction.", body_style)) story.append(section_box("Classification")) class3_data = [ [Paragraph(b("Type"), body_style), Paragraph(b("Features"), body_style)], [Paragraph("Extrinsic / Allergic / Atopic", body_style), Paragraph("Most common. IgE-mediated. Starts in childhood. Triggers: dust mites, pollen, animal dander, molds. " "Positive family history. Positive skin prick test. Raised total IgE.", body_style)], [Paragraph("Intrinsic / Non-allergic", body_style), Paragraph("No identifiable allergen. Adult onset. Triggers: infections (viral URTI), cold air, exercise, aspirin, NSAIDs, " "occupational agents (isocyanates), emotions. Normal IgE.", body_style)], [Paragraph("Mixed", body_style), Paragraph("Features of both types.", body_style)], [Paragraph("Occupational Asthma", body_style), Paragraph("Due to workplace sensitizers — isocyanates, flour dust, latex.", body_style)], [Paragraph("Exercise-induced", body_style), Paragraph("Triggered by vigorous exercise; bronchoconstriction during or after exercise.", body_style)], [Paragraph("Aspirin-sensitive (Samter's Triad)", body_style), Paragraph("Asthma + nasal polyps + aspirin sensitivity.", body_style)], ] class3_table = Table(class3_data, colWidths=[5*cm, 12*cm]) class3_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(class3_table) story.append(Spacer(1, 0.15*cm)) story.append(section_box("Pathophysiology")) story.append(Paragraph(b("Early Phase Reaction (immediate, 0-30 min):"), bold_label)) for item in [ "Antigen binds IgE on mast cells → mast cell degranulation", "Release of: histamine, leukotrienes (LTC4, LTD4), prostaglandins, bradykinin", "Bronchoconstriction, vasodilation, increased mucus secretion, mucosal edema", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Late Phase Reaction (3-12 hours):"), bold_label)) for item in [ "Recruitment of eosinophils, neutrophils, T-lymphocytes → chronic inflammation", "Eosinophil-derived proteins cause epithelial damage and airway remodeling", "Bronchial hyperresponsiveness established", b("Airway remodeling") + ": subepithelial fibrosis, goblet cell hyperplasia, smooth muscle hypertrophy → irreversible narrowing", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Clinical Features")) story.append(Paragraph(b("Classic Triad:"), bold_label)) story.append(Paragraph("• Wheeze (expiratory) • Cough (nocturnal, worse at night/early morning) • Breathlessness (dyspnea)", body_style)) story.append(Paragraph(b("During an Acute Attack:"), bold_label)) for item in [ "Breathlessness, tachypnoea, use of accessory muscles of respiration", "Expiratory wheeze and prolonged expiration", "Tachycardia, anxiety, patient prefers to sit upright", b("Signs of severity") + ": cyanosis, pulsus paradoxus, unable to speak, silent chest (ominous — no air entry)", "Hyperinflated chest — barrel-shaped in chronic asthma", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Investigations")) story.append(Paragraph(b("Pulmonary Function Tests (PFTs) — Cornerstone of Diagnosis:"), bold_label)) for item in [ b("Spirometry") + ": FEV1/FVC ratio <70% (obstructive pattern); >12% and 200 mL improvement in FEV1 post-bronchodilator = reversibility", b("Peak Expiratory Flow Rate (PEFR)") + ": reduced during attack; >20% diurnal variation is diagnostic", b("Methacholine challenge test") + ": airway hyperresponsiveness (used when diagnosis uncertain)", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Other Tests:"), bold_label)) for item in [ b("CXR") + ": hyperinflation, may show pneumothorax in severe attack (usually normal between attacks)", b("Sputum") + ": eosinophils, Charcot-Leyden crystals, Curschmann's spirals", b("Blood CBC") + ": eosinophilia", b("Skin prick test / RAST") + ": identify specific allergens", b("Total & specific IgE") + ": elevated in atopic asthma", b("ABG") + ": in severe attack — hypoxemia; initial hypocapnia, then hypercapnia = impending respiratory failure", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(section_box("Management")) story.append(Paragraph(b("Step-Up Approach (GINA/NAEPP Guidelines):"), bold_label)) step_data = [ [Paragraph(b("Step"), body_style), Paragraph(b("Severity"), body_style), Paragraph(b("Treatment"), body_style)], [Paragraph("Step 1", body_style), Paragraph("Intermittent", body_style), Paragraph("SABA (Salbutamol/Albuterol) PRN only", body_style)], [Paragraph("Step 2", body_style), Paragraph("Mild persistent", body_style), Paragraph("Low-dose ICS (Beclomethasone) + SABA PRN", body_style)], [Paragraph("Step 3", body_style), Paragraph("Moderate persistent", body_style), Paragraph("Low/Medium ICS + LABA (Salmeterol/Formoterol)", body_style)], [Paragraph("Step 4", body_style), Paragraph("Severe persistent", body_style), Paragraph("Medium/High ICS + LABA ± LAMA (Tiotropium)", body_style)], [Paragraph("Step 5", body_style), Paragraph("Very severe", body_style), Paragraph("Oral corticosteroids / Biologic therapy (Omalizumab for atopic, Mepolizumab for eosinophilic)", body_style)], ] step_table = Table(step_data, colWidths=[2.5*cm, 4*cm, 10.5*cm]) step_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(step_table) story.append(Spacer(1, 0.1*cm)) story.append(Paragraph(b("Key Drug Groups:"), bold_label)) drug_data = [ [Paragraph(b("Drug"), body_style), Paragraph(b("Class"), body_style), Paragraph(b("Role"), body_style)], [Paragraph("Salbutamol (Albuterol)", body_style), Paragraph("SABA", body_style), Paragraph("Reliever — bronchodilator, rapid onset, first-line in acute attack", body_style)], [Paragraph("Salmeterol, Formoterol", body_style), Paragraph("LABA", body_style), Paragraph("Controller — not for acute relief; always with ICS", body_style)], [Paragraph("Beclomethasone, Budesonide, Fluticasone", body_style), Paragraph("ICS", body_style), Paragraph("Mainstay of prevention; reduce inflammation, most effective controller", body_style)], [Paragraph("Prednisolone", body_style), Paragraph("Oral steroid", body_style), Paragraph("Acute severe attack and step 5 maintenance", body_style)], [Paragraph("Ipratropium", body_style), Paragraph("SAMA", body_style), Paragraph("Add-on bronchodilator in severe attack (nebulized)", body_style)], [Paragraph("Montelukast", body_style), Paragraph("LTRA", body_style), Paragraph("Leukotriene receptor antagonist; useful in aspirin-sensitive asthma", body_style)], [Paragraph("Theophylline", body_style), Paragraph("Methylxanthine", body_style), Paragraph("Add-on; narrow therapeutic index; monitor levels", body_style)], [Paragraph("Omalizumab", body_style), Paragraph("Anti-IgE biologic", body_style), Paragraph("Severe allergic asthma uncontrolled on step 4", body_style)], ] drug_table = Table(drug_data, colWidths=[5*cm, 3*cm, 9*cm]) drug_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')), ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]), ])) story.append(drug_table) story.append(Spacer(1, 0.1*cm)) story.append(section_box("Management of Acute Severe Asthma (Status Asthmaticus)")) for item in [ b("Sit upright") + ", high-flow O2 (40-60% to maintain SpO2 >94%)", b("Nebulized Salbutamol") + " 2.5-5 mg every 20 min x3, then hourly", b("Add Nebulized Ipratropium") + " 0.5 mg — if not responding", b("IV Hydrocortisone") + " 200 mg stat (or Prednisolone 40-50 mg oral)", b("IV Magnesium Sulfate") + " 1.2-2g over 20 min — smooth muscle relaxant (if FEV1 <30%)", b("IV Aminophylline") + " — for those not on theophylline already", b("NIV/Mechanical ventilation") + " — if deteriorating despite all measures", ]: story.append(Paragraph(f"• {item}", bullet_style)) story.append(Paragraph(b("Dental Relevance:"), bold_label)) story.append(Paragraph( "Asthmatic patients need special dental care: (1) Always have salbutamol inhaler available in clinic. " "(2) Avoid aspirin/NSAIDs — use paracetamol for analgesia. " "(3) Avoid bisulfite-containing local anesthetics (rare trigger). " "(4) Stress, anxiety, and cold dry air can trigger bronchospasm — use anxiolysis if needed. " "(5) Erythromycin increases theophylline levels (theophylline toxicity risk). " "(6) Inhaled steroids may cause oral candidiasis — advise rinsing mouth after use.", body_style)) story.append(Spacer(1, 0.3*cm)) story.append(HRFlowable(width="100%", thickness=1, color=colors.HexColor('#9fa8da'))) story.append(Spacer(1, 0.2*cm)) story.append(Paragraph( "General Medicine Short Notes | BDS 3rd Year | Gujarat University | " "Based on Anil K. Tripathi — General Medicine for BDS", footer_style)) doc.build(story) print("PDF generated successfully!") EOF

Writing File

~/bds-notes/generate_notes.py

from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY

doc = SimpleDocTemplate(
    "/tmp/workspace/bds-notes/General_Medicine_Short_Notes_BDS.pdf",
    pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2*cm, bottomMargin=2*cm
)

styles = getSampleStyleSheet()

title_style = ParagraphStyle(
    'MainTitle', parent=styles['Title'],
    fontSize=18, textColor=colors.HexColor('#1a237e'),
    spaceAfter=4, alignment=TA_CENTER, fontName='Helvetica-Bold'
)
subtitle_style = ParagraphStyle(
    'SubTitle', parent=styles['Normal'],
    fontSize=10, textColor=colors.HexColor('#4a4a4a'),
    spaceAfter=12, alignment=TA_CENTER, fontName='Helvetica-Oblique'
)
body_style = ParagraphStyle(
    'Body', parent=styles['Normal'],
    fontSize=9.5, textColor=colors.HexColor('#212121'),
    spaceAfter=3, spaceBefore=1,
    leading=14, alignment=TA_JUSTIFY, fontName='Helvetica'
)
bullet_style = ParagraphStyle(
    'Bullet', parent=styles['Normal'],
    fontSize=9.5, textColor=colors.HexColor('#212121'),
    spaceAfter=2, spaceBefore=1,
    leading=13, leftIndent=14, bulletIndent=4,
    fontName='Helvetica'
)
bold_label = ParagraphStyle(
    'BoldLabel', parent=styles['Normal'],
    fontSize=9.5, textColor=colors.HexColor('#1a237e'),
    spaceAfter=1, spaceBefore=3,
    fontName='Helvetica-Bold'
)
footer_style = ParagraphStyle(
    'Footer', parent=styles['Normal'],
    fontSize=8, textColor=colors.HexColor('#757575'),
    alignment=TA_CENTER
)

def topic_banner(title, number):
    data = [[Paragraph('<font color="white"><b>TOPIC %s: %s</b></font>' % (number, title), ParagraphStyle(
        'banner', fontSize=13, textColor=colors.white,
        fontName='Helvetica-Bold', alignment=TA_LEFT
    ))]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#1a237e')),
        ('TOPPADDING', (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
    ]))
    return t

def section_box(title):
    data = [[Paragraph('<b>%s</b>' % title, ParagraphStyle(
        'sbox', fontSize=10, textColor=colors.HexColor('#1a237e'),
        fontName='Helvetica-Bold'
    ))]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#e8eaf6')),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 8),
        ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor('#3949ab')),
    ]))
    return t

def make_table(data_list, col_widths, header=True):
    t = Table(data_list, colWidths=col_widths)
    style_cmds = [
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
    ]
    if header:
        style_cmds.append(('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')))
    style_cmds.append(('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f5f5f5')]))
    t.setStyle(TableStyle(style_cmds))
    return t

def bp(text):
    return '<b>%s</b>' % text

story = []

# HEADER
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph("GENERAL MEDICINE", title_style))
story.append(Paragraph("Short Notes for BDS 3rd Year | Gujarat University Examinations", subtitle_style))
story.append(Paragraph("Based on Anil K. Tripathi - General Medicine for BDS", ParagraphStyle(
    'ref', fontSize=9, textColor=colors.HexColor('#757575'),
    alignment=TA_CENTER, fontName='Helvetica-Oblique', spaceAfter=4
)))
story.append(Paragraph("Each topic: 7-8 Marks | Concise, Precise, Exam-Oriented", ParagraphStyle(
    'info', fontSize=9, textColor=colors.HexColor('#e53935'),
    alignment=TA_CENTER, fontName='Helvetica-Bold', spaceAfter=10
)))
story.append(HRFlowable(width="100%", thickness=2, color=colors.HexColor('#1a237e')))
story.append(Spacer(1, 0.3*cm))

toc_data = [
    [Paragraph(bp("No."), body_style), Paragraph(bp("Topic"), body_style), Paragraph(bp("Marks"), body_style)],
    [Paragraph("1.", body_style), Paragraph("Syncope", body_style), Paragraph("7-8", body_style)],
    [Paragraph("2.", body_style), Paragraph("Arrhythmia", body_style), Paragraph("7-8", body_style)],
    [Paragraph("3.", body_style), Paragraph("Pneumonia", body_style), Paragraph("7-8", body_style)],
    [Paragraph("4.", body_style), Paragraph("Lung Abscess", body_style), Paragraph("7-8", body_style)],
    [Paragraph("5.", body_style), Paragraph("Bronchial Asthma", body_style), Paragraph("7-8", body_style)],
]
toc_table = Table(toc_data, colWidths=[1.5*cm, 13*cm, 2.5*cm])
toc_table.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8eaf6')),
    ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#9fa8da')),
    ('ALIGN', (2,0), (2,-1), 'CENTER'),
    ('TOPPADDING', (0,0), (-1,-1), 4),
    ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ('LEFTPADDING', (0,0), (-1,-1), 8),
]))
story.append(toc_table)
story.append(Spacer(1, 0.5*cm))
story.append(PageBreak())

# ============================================================
# TOPIC 1: SYNCOPE
# ============================================================
story.append(topic_banner("SYNCOPE", "1"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Syncope is a transient, self-limited loss of consciousness (TLOC) due to global cerebral hypoperfusion, "
    "characterized by a rapid onset, short duration, and spontaneous complete recovery, without neurological deficit.",
    body_style))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Etiology / Classification"))
etiology_data = [
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Causes"), body_style)],
    [Paragraph("Vasovagal (Neurocardiogenic)", body_style),
     Paragraph("Most common. Triggered by emotional stress, pain, prolonged standing, sight of blood. Due to paradoxical bradycardia + hypotension.", body_style)],
    [Paragraph("Cardiac", body_style),
     Paragraph("Arrhythmias (VT, VF, sick sinus syndrome, complete heart block), aortic stenosis, HOCM, massive MI, cardiac tamponade.", body_style)],
    [Paragraph("Orthostatic Hypotension", body_style),
     Paragraph("Drop in SBP >20 mmHg on standing. Causes: dehydration, drugs (antihypertensives, diuretics), autonomic neuropathy (diabetes), Addison's disease.", body_style)],
    [Paragraph("Situational", body_style),
     Paragraph("Micturition syncope, cough syncope, swallowing syncope, defecation syncope.", body_style)],
    [Paragraph("Carotid Sinus", body_style),
     Paragraph("Hypersensitive carotid sinus reflex; provoked by neck turning, tight collar.", body_style)],
    [Paragraph("Neurological", body_style),
     Paragraph("Vertebrobasilar TIA, subclavian steal syndrome (rare causes).", body_style)],
]
story.append(make_table(etiology_data, [5*cm, 12*cm]))
story.append(Spacer(1, 0.15*cm))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Pre-syncopal Prodrome (Warning symptoms):"), bold_label))
for item in [
    "Dizziness, lightheadedness, nausea, sweating",
    "Blurring / greying out of vision, ringing in ears (tinnitus)",
    "Pallor, generalized weakness - lasts seconds to minutes",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("During syncope:"), bold_label))
for item in [
    "Sudden loss of consciousness and postural tone",
    "Patient falls - may sustain injury",
    "Brief tonic-clonic jerks possible (not a true seizure) if ischemia prolonged",
    "Pallor, slow weak pulse, dilated pupils",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Post-syncopal:"), bold_label))
for item in [
    "Rapid spontaneous recovery on becoming supine (within seconds)",
    "No post-ictal confusion (key differentiator from epileptic seizure)",
    "Mild fatigue or headache may persist briefly",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Investigations"))
for item in [
    bp("History") + " - detailed history of trigger, prodrome, duration, recovery (most important diagnostic tool)",
    bp("ECG") + " - detect arrhythmias, heart block, QT prolongation, Brugada syndrome",
    bp("Holter Monitor / Event Recorder") + " - paroxysmal arrhythmias; implantable loop recorder for recurrent unexplained syncope",
    bp("Echocardiography") + " - structural heart disease (aortic stenosis, HOCM)",
    bp("Tilt Table Test") + " - suspected vasovagal / orthostatic syncope",
    bp("Carotid Sinus Massage") + " - carotid sinus hypersensitivity (monitored setting only)",
    bp("Blood Tests") + " - CBC, blood glucose, electrolytes to exclude metabolic causes",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment"))
story.append(Paragraph(bp("General / Vasovagal:"), bold_label))
for item in [
    "Place patient supine, elevate legs to restore cerebral perfusion",
    "Patient education: avoid triggers, dehydration",
    "Physical counter-pressure maneuvers (leg crossing, hand gripping)",
    "Increased salt and fluid intake",
    "Beta-blockers (atenolol) in selected cases; midodrine for orthostatic type",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Cardiac Syncope:"), bold_label))
for item in [
    "Treat underlying arrhythmia - pacemaker for bradyarrhythmias",
    "ICD (implantable cardioverter-defibrillator) for VT/VF",
    "Surgery for structural lesions (aortic stenosis, HOCM)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    bp("Vasovagal syncope is the most common medical emergency in dental practice.") + " "
    "Prevention: treat anxious patients in supine/semi-reclined position, adequate analgesia, minimize waiting time. "
    "Management: lay patient flat, elevate legs, loosen tight clothing, ensure airway patent. "
    "Atropine 0.6 mg IV if persistent bradycardia.",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 2: ARRHYTHMIA
# ============================================================
story.append(topic_banner("ARRHYTHMIA", "2"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Arrhythmia (or dysrhythmia) is any disturbance in the normal rate, rhythm, site of origin, or conduction "
    "of the cardiac electrical impulse. Normal sinus rhythm: rate 60-100 bpm, P wave precedes every QRS complex.",
    body_style))

story.append(section_box("Classification"))
class_data = [
    [Paragraph(bp("Category"), body_style), Paragraph(bp("Types"), body_style)],
    [Paragraph("By Rate", body_style),
     Paragraph("Bradyarrhythmia (<60 bpm) | Tachyarrhythmia (>100 bpm)", body_style)],
    [Paragraph("Supraventricular\n(above Bundle of His)", body_style),
     Paragraph("Sinus tachycardia, Sinus bradycardia, SVT, Atrial fibrillation (AF), Atrial flutter, AVNRT, WPW syndrome, Junctional rhythm", body_style)],
    [Paragraph("Ventricular", body_style),
     Paragraph("PVCs, Ventricular tachycardia (VT), Ventricular fibrillation (VF), Torsades de pointes", body_style)],
    [Paragraph("Conduction Defects", body_style),
     Paragraph("1st, 2nd (Mobitz I & II), 3rd degree AV block; Bundle branch blocks (LBBB, RBBB); Sick sinus syndrome", body_style)],
]
story.append(make_table(class_data, [5*cm, 12*cm]))
story.append(Spacer(1, 0.15*cm))

story.append(section_box("Important Arrhythmias - Key Features"))

story.append(Paragraph(bp("1. Atrial Fibrillation (AF)"), bold_label))
for item in [
    "Most common sustained cardiac arrhythmia",
    "Chaotic, irregular atrial activity at 350-600 impulses/min",
    bp("ECG") + ": absent P waves, irregularly irregular QRS, fibrillatory baseline",
    bp("Causes") + ": hypertension, rheumatic heart disease, thyrotoxicosis, IHD, alcohol ('holiday heart')",
    bp("Risks") + ": embolic stroke (thrombus in left atrial appendage), heart failure",
    bp("Treatment") + ": Rate control (beta-blockers, digoxin, CCBs) | Rhythm control (cardioversion, amiodarone) | Anticoagulation (warfarin/NOAC) to prevent stroke",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("2. Ventricular Tachycardia (VT)"), bold_label))
for item in [
    "3 or more consecutive ventricular beats at rate >100 bpm",
    bp("ECG") + ": wide QRS (>0.12s), AV dissociation, fusion beats, capture beats",
    bp("Causes") + ": MI, cardiomyopathy, electrolyte disturbances (hypokalemia, hypomagnesemia)",
    bp("Treatment") + ": Stable VT - IV amiodarone/lignocaine; Unstable VT - DC cardioversion; ICD for recurrent VT",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("3. Complete Heart Block (3rd Degree AV Block)"), bold_label))
for item in [
    "Complete dissociation between atrial and ventricular activity",
    bp("ECG") + ": P waves and QRS complexes independent of each other; slow ventricular escape rhythm (20-40 bpm)",
    bp("Symptoms") + ": Stokes-Adams attacks (sudden transient LOC), heart failure, severe bradycardia",
    bp("Treatment") + ": Permanent pacemaker implantation",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("4. Sick Sinus Syndrome"), bold_label))
for item in [
    "Dysfunction of SA node: bradycardia, SA block, sinus arrest",
    "Brady-tachy syndrome: alternates with tachyarrhythmias",
    bp("Treatment") + ": Permanent pacemaker",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Investigations"))
for item in [
    bp("ECG (12-lead)") + " - single most important investigation",
    bp("Holter Monitor") + " - 24-48 hour ambulatory ECG for paroxysmal arrhythmias",
    bp("Electrophysiological Study (EPS)") + " - for complex arrhythmias, pre-ablation",
    bp("Echocardiography") + " - assess structural heart disease",
    bp("Blood tests") + " - electrolytes (K+, Mg2+), thyroid function tests (TFTs), cardiac enzymes",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment Summary"))
treat_data = [
    [Paragraph(bp("Approach"), body_style), Paragraph(bp("Details"), body_style)],
    [Paragraph("Rate Control", body_style), Paragraph("Beta-blockers, CCBs (verapamil, diltiazem), digoxin", body_style)],
    [Paragraph("Rhythm Control", body_style), Paragraph("Antiarrhythmics: amiodarone, flecainide, sotalol; DC cardioversion", body_style)],
    [Paragraph("Pacemakers", body_style), Paragraph("Bradyarrhythmias, complete heart block, sick sinus syndrome", body_style)],
    [Paragraph("ICD", body_style), Paragraph("VT/VF; high-risk patients with structural heart disease", body_style)],
    [Paragraph("Catheter Ablation", body_style), Paragraph("SVT, WPW syndrome, AF - radiofrequency ablation", body_style)],
    [Paragraph("Anticoagulation", body_style), Paragraph("AF - warfarin (INR 2-3) or NOACs (rivaroxaban, apixaban, dabigatran)", body_style)],
]
story.append(make_table(treat_data, [4*cm, 13*cm]))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    "Patients on " + bp("warfarin") + ": check INR before extraction (safe if INR <3.5 for minor dental surgery). "
    "Avoid epinephrine-containing LA in severe arrhythmias or digoxin toxicity. "
    bp("Erythromycin / clarithromycin") + " can prolong QT interval - use cautiously. "
    "Epinephrine in LA is safe in controlled arrhythmia if used in low dose (max 2 cartridges).",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 3: PNEUMONIA
# ============================================================
story.append(topic_banner("PNEUMONIA", "3"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Pneumonia is an acute inflammatory condition of the lung parenchyma (alveoli, alveolar ducts, and respiratory bronchioles) "
    "caused by microbial infection, resulting in consolidation and impaired gas exchange.",
    body_style))

story.append(section_box("Classification"))
class2_data = [
    [Paragraph(bp("By Setting"), body_style), Paragraph(bp("By Etiology"), body_style), Paragraph(bp("By Anatomy"), body_style)],
    [Paragraph("- Community-Acquired (CAP)\n- Hospital-Acquired (HAP) - >48h after admission\n- Ventilator-Associated (VAP)\n- Aspiration Pneumonia\n- Immunocompromised Host", body_style),
     Paragraph("- Bacterial: S. pneumoniae (MC), Staphylococcus, Klebsiella, H. influenzae\n- Atypical: Mycoplasma, Chlamydia, Legionella\n- Viral: Influenza, COVID-19, RSV\n- Fungal: PCP (immunocompromised)", body_style),
     Paragraph("- Lobar pneumonia (entire lobe)\n- Bronchopneumonia (patchy, multifocal)\n- Interstitial pneumonia (alveolar walls)", body_style)],
]
story.append(make_table(class2_data, [5.5*cm, 7.5*cm, 4*cm]))
story.append(Spacer(1, 0.15*cm))

story.append(section_box("Pathology - Stages of Lobar Pneumonia"))
path_data = [
    [Paragraph(bp("Stage"), body_style), Paragraph(bp("Duration"), body_style), Paragraph(bp("Features"), body_style)],
    [Paragraph("1. Congestion", body_style), Paragraph("1-2 days", body_style),
     Paragraph("Vascular engorgement, edema fluid, bacteria; lung heavy, boggy", body_style)],
    [Paragraph("2. Red Hepatization", body_style), Paragraph("2-4 days", body_style),
     Paragraph("Lobe firm like liver; alveoli filled with RBCs, fibrin, PMNs", body_style)],
    [Paragraph("3. Grey Hepatization", body_style), Paragraph("4-8 days", body_style),
     Paragraph("RBCs lysed; alveoli filled with fibrin, PMNs, macrophages; grey-brown color", body_style)],
    [Paragraph("4. Resolution", body_style), Paragraph("8-9 days", body_style),
     Paragraph("Enzymatic digestion of exudate; normal lung architecture restored", body_style)],
]
story.append(make_table(path_data, [4.5*cm, 2.5*cm, 10*cm]))
story.append(Spacer(1, 0.15*cm))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Symptoms:"), bold_label))
for item in [
    bp("Sudden onset") + " high-grade fever (39-40 degrees C) with rigors/chills",
    bp("Productive cough") + " - rusty/blood-tinged sputum (characteristic of pneumococcal pneumonia)",
    bp("Pleuritic chest pain") + " - sharp, worse on deep inspiration",
    "Breathlessness, tachypnoea",
    "Herpes labialis (cold sores) on lips",
    "Malaise, anorexia, headache",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs:"), bold_label))
exam_data = [
    [Paragraph(bp("Method"), body_style), Paragraph(bp("Finding"), body_style)],
    [Paragraph("Inspection", body_style), Paragraph("Reduced chest expansion on affected side, tachypnoea", body_style)],
    [Paragraph("Palpation", body_style), Paragraph("Increased vocal fremitus over consolidation", body_style)],
    [Paragraph("Percussion", body_style), Paragraph("Dull note over consolidated lobe", body_style)],
    [Paragraph("Auscultation", body_style), Paragraph("Bronchial breathing, increased vocal resonance, crepitations (crackles), pleural friction rub", body_style)],
]
story.append(make_table(exam_data, [4*cm, 13*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Investigations"))
for item in [
    bp("Chest X-ray") + " - consolidation (homogeneous opacity), air bronchogram sign; most important",
    bp("Sputum Gram stain and culture") + " - identify organism and sensitivity",
    bp("CBC") + " - neutrophilic leukocytosis (bacterial); lymphocytosis (viral/atypical)",
    bp("Blood culture") + " - bacteremia in severe cases",
    bp("ABG") + " - assess degree of hypoxemia",
    bp("Urine antigen tests") + " - Legionella and Streptococcal pneumococcal antigens",
    bp("Serology") + " - Mycoplasma, Chlamydia, Legionella (cold agglutinins in Mycoplasma)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment"))
story.append(Paragraph(bp("Severity Assessment - CURB-65 Score:"), bold_label))
story.append(Paragraph(
    bp("C") + "=Confusion | " + bp("U") + "=Urea >7 mmol/L | " + bp("R") + "=RR >=30/min | "
    + bp("B") + "=BP systolic <90 or diastolic <=60 | " + bp("65") + "=Age >=65 years. "
    "Score 0-1: treat at home; Score 2: hospital admission; Score >=3: consider ICU.",
    body_style))

story.append(Paragraph(bp("Antibiotic Therapy (CAP):"), bold_label))
for item in [
    bp("Mild/Outpatient") + ": Amoxicillin 500 mg TDS x 5-7 days; or Doxycycline/Clarithromycin for atypical cover",
    bp("Moderate/Hospital") + ": IV Co-amoxiclav + Clarithromycin",
    bp("Severe/ICU") + ": IV Piperacillin-tazobactam + IV Levofloxacin/Azithromycin",
    bp("Aspiration pneumonia") + ": Metronidazole + Co-amoxiclav (anaerobic coverage)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Supportive Treatment:"), bold_label))
for item in [
    "Oxygen supplementation (target SpO2 >94%)",
    "IV fluids, antipyretics, analgesics",
    "Physiotherapy and postural drainage",
    "Mechanical ventilation if severe respiratory failure (ARDS)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Complications:"), bold_label))
for item in [
    "Pleural effusion / Empyema",
    "Lung abscess",
    "Respiratory failure (ARDS)",
    "Septicemia, septic shock",
    "Hepatitis (atypical pneumonia - Mycoplasma)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    bp("Aspiration pneumonia") + " can result from dental procedures - especially in patients under GA or sedation "
    "with impaired gag reflex. Oral anaerobes from periodontal disease are common culprits. "
    "Good oral hygiene reduces aspiration pneumonia risk in hospitalized and elderly patients.",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 4: LUNG ABSCESS
# ============================================================
story.append(topic_banner("LUNG ABSCESS", "4"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Lung abscess is a localized area of suppuration (pus formation) within the pulmonary parenchyma, "
    "leading to necrosis and cavity formation (usually >2 cm in diameter) containing purulent material. "
    "May be " + bp("primary") + " (no pre-existing disease) or " + bp("secondary") + " (complication of existing disease).",
    body_style))

story.append(section_box("Etiology and Predisposing Factors"))
story.append(Paragraph(bp("Causative Organisms:"), bold_label))
for item in [
    bp("Anaerobes (most common)") + " - Bacteroides, Fusobacterium, Peptostreptococcus, Prevotella (oral commensals)",
    bp("Aerobes") + " - Staphylococcus aureus, Klebsiella pneumoniae, Pseudomonas, Streptococcus pyogenes",
    "Mixed flora in most cases; anaerobes present in 1/3 to 2/3 of cases as sole isolates",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Pathways of Infection:"), bold_label))
path2_data = [
    [Paragraph(bp("Mechanism"), body_style), Paragraph(bp("Details"), body_style)],
    [Paragraph("Aspiration (MC)", body_style),
     Paragraph("Infected material from carious teeth, periodontitis, sinuses, tonsils. Precipitated by: unconsciousness, GA, alcohol intoxication, epilepsy, dysphagia, debilitated state.", body_style)],
    [Paragraph("Complication of Pneumonia", body_style),
     Paragraph("Necrotizing bacterial pneumonia - S. aureus, Klebsiella, Pseudomonas, type 3 pneumococcus.", body_style)],
    [Paragraph("Bronchial Obstruction", body_style),
     Paragraph("Carcinoma of lung, foreign body - impaired drainage + distal infection.", body_style)],
    [Paragraph("Hematogenous Spread", body_style),
     Paragraph("Septic emboli from right-sided infective endocarditis, IV drug abuse - multiple bilateral abscesses.", body_style)],
    [Paragraph("Others", body_style),
     Paragraph("Subphrenic abscess (trans-diaphragmatic), penetrating chest trauma.", body_style)],
]
story.append(make_table(path2_data, [4.5*cm, 12.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Site of Predilection"))
story.append(Paragraph(
    bp("Right lung") + " more commonly affected (right bronchus more vertical). "
    "In " + bp("recumbent position") + " (most aspiration cases): posterior segment of right upper lobe and apical segment of right lower lobe. "
    "In " + bp("upright position") + ": basal segments of lower lobes. "
    "Hematogenous abscesses: multiple, bilateral, any lobe.",
    body_style))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Acute Phase (before bronchial rupture):"), bold_label))
for item in [
    "High-grade fever with rigors, drenching sweats, toxemia",
    "Pleuritic chest pain",
    "Dry cough, malaise, weight loss, anorexia",
    "No or minimal sputum production",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Drainage Phase (after cavity ruptures into bronchus):"), bold_label))
for item in [
    bp("Hallmark") + ": sudden expectoration of large amounts of " + bp("foul-smelling, purulent sputum") + " (copious - 'cupful' in 24h)",
    "Sputum settles into 3 layers: frothy (top) / watery (middle) / purulent necrotic (bottom) - characteristic",
    "Blood-stained sputum (hemoptysis)",
    "Improvement of fever after drainage",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs:"), bold_label))
for item in [
    "Clubbing (chronic cases)",
    "Dullness to percussion over the abscess",
    bp("Amphoric / cavernous breathing") + " over the cavity (distinctive sign)",
    "Coarse crepitations",
    "Signs of surrounding consolidation",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Investigations"))
for item in [
    bp("Chest X-ray") + " - " + bp("thick-walled cavity with air-fluid level") + " (most characteristic finding); usually right-sided",
    bp("CT Chest") + " - better delineation; distinguishes from empyema and cavitating carcinoma",
    bp("Sputum") + " - Gram stain, aerobic + anaerobic culture and sensitivity; cytology for malignancy",
    bp("Bronchoscopy") + " - exclude underlying carcinoma or foreign body; obtain specimens",
    bp("CBC") + " - neutrophilic leukocytosis, raised ESR, anemia (chronic)",
    bp("Blood culture") + " - hematogenous cases",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment"))
story.append(Paragraph(bp("Medical (First Line - most abscesses respond):"), bold_label))
for item in [
    bp("Antibiotics") + ": IV " + bp("Clindamycin") + " (drug of choice for aspiration/anaerobic lung abscess); or Co-amoxiclav + Metronidazole",
    "Duration: " + bp("6-8 weeks") + " (until radiological resolution)",
    bp("Postural drainage + chest physiotherapy") + " - position abscess uppermost to promote drainage",
    "Adequate nutrition (high protein diet), hydration",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Surgical (for failed/complicated cases):"), bold_label))
for item in [
    bp("Percutaneous CT-guided drainage") + " - large peripheral abscesses",
    bp("Bronchoscopic drainage") + " - if endobronchial obstruction",
    bp("Lobectomy/Pneumonectomy") + " - chronic non-resolving abscess, >6 cm, underlying malignancy",
    bp("Indications for surgery") + ": no response to 6 weeks antibiotics, abscess >6 cm, massive hemoptysis, malignancy",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Complications:"), bold_label))
for item in [
    "Empyema / Pyopneumothorax",
    "Massive hemoptysis",
    "Septicemia, metastatic abscess (brain abscess)",
    "Bronchiectasis (chronic)",
    "Respiratory failure",
    "Amyloidosis (very chronic cases)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    bp("Dental sepsis and poor oral hygiene are the most important predisposing factors for aspiration lung abscess.") + " "
    "Oral anaerobes (Bacteroides, Fusobacterium, Peptostreptococcus) are the principal organisms. "
    "Risk is highest during GA for dental procedures. "
    "Pre-operative oral hygiene optimization and antibiotic prophylaxis reduce risk.",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 5: BRONCHIAL ASTHMA
# ============================================================
story.append(topic_banner("BRONCHIAL ASTHMA", "5"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Bronchial asthma is a chronic inflammatory disease of the airways characterized by: "
    "(1) " + bp("Airway hyperresponsiveness") + " to various stimuli, "
    "(2) " + bp("Reversible airflow obstruction") + " (spontaneously or with treatment), and "
    "(3) " + bp("Chronic airway inflammation") + " with mucosal edema, mucus hypersecretion, and bronchoconstriction.",
    body_style))

story.append(section_box("Classification"))
class3_data = [
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Features"), body_style)],
    [Paragraph("Extrinsic / Allergic / Atopic", body_style),
     Paragraph("Most common. IgE-mediated. Onset in childhood. Triggers: dust mites, pollen, animal dander, molds. Positive family history. Raised total IgE. Positive skin prick test.", body_style)],
    [Paragraph("Intrinsic / Non-allergic", body_style),
     Paragraph("No identifiable allergen. Adult onset. Triggers: viral URTI, cold air, exercise, aspirin/NSAIDs, occupational agents (isocyanates, latex), emotions. Normal IgE.", body_style)],
    [Paragraph("Occupational", body_style),
     Paragraph("Workplace sensitizers: isocyanates, flour dust, latex, formaldehyde.", body_style)],
    [Paragraph("Aspirin-sensitive\n(Samter's Triad)", body_style),
     Paragraph("Asthma + nasal polyps + aspirin/NSAID sensitivity.", body_style)],
    [Paragraph("Exercise-Induced", body_style),
     Paragraph("Bronchoconstriction triggered by vigorous exercise.", body_style)],
]
story.append(make_table(class3_data, [5*cm, 12*cm]))
story.append(Spacer(1, 0.15*cm))

story.append(section_box("Pathophysiology"))
story.append(Paragraph(bp("Early Phase Reaction (Immediate, 0-30 min):"), bold_label))
for item in [
    "Antigen binds IgE on mast cells and basophils - mast cell degranulation",
    "Release of: histamine, leukotrienes (LTC4, LTD4, LTE4), prostaglandins (PGD2), bradykinin",
    "Results in: bronchoconstriction, vasodilation, increased vascular permeability, mucus hypersecretion",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Late Phase Reaction (3-12 hours):"), bold_label))
for item in [
    "Recruitment of eosinophils, neutrophils, T-lymphocytes, basophils - chronic inflammation",
    "Eosinophil-derived major basic protein (MBP) causes epithelial damage",
    "Bronchial hyperresponsiveness established",
    bp("Airway remodeling") + ": subepithelial fibrosis, goblet cell hyperplasia, smooth muscle hypertrophy, angiogenesis - may lead to irreversible narrowing",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Classic Triad: Episodic Wheeze + Cough + Breathlessness"), bold_label))
for item in [
    bp("Wheeze") + " - expiratory (musical); worse at night and early morning",
    bp("Cough") + " - often nocturnal, dry or productive; can be the only symptom (cough-variant asthma)",
    bp("Breathlessness (dyspnoea)") + " - episodic, precipitated by triggers",
    "Symptoms are " + bp("reversible") + " and " + bp("episodic") + "; symptom-free between attacks",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("During an Acute Severe Attack:"), bold_label))
for item in [
    "Severe breathlessness, tachypnoea, use of accessory muscles",
    "Expiratory wheeze and prolonged expiration",
    "Tachycardia, patient sits upright unable to lie flat",
    "Pulsus paradoxus (>10 mmHg drop in systolic BP on inspiration)",
    bp("Danger signs") + ": cyanosis, inability to speak, " + bp("silent chest") + " (no wheeze - no air entry - ominous), bradycardia",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Investigations"))
story.append(Paragraph(bp("Pulmonary Function Tests (PFTs) - Most Important:"), bold_label))
pft_data = [
    [Paragraph(bp("Test"), body_style), Paragraph(bp("Finding"), body_style)],
    [Paragraph("Spirometry", body_style),
     Paragraph("FEV1/FVC ratio <70% (obstructive). Post-bronchodilator: >=12% AND >=200 mL rise in FEV1 = reversibility (diagnostic of asthma)", body_style)],
    [Paragraph("PEFR (Peak Flow)", body_style),
     Paragraph("Reduced during attack. >20% diurnal variation (morning dip) is diagnostic.", body_style)],
    [Paragraph("Methacholine Challenge", body_style),
     Paragraph("Provocation test to confirm airway hyperresponsiveness when diagnosis uncertain.", body_style)],
]
story.append(make_table(pft_data, [4.5*cm, 12.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Other Investigations:"), bold_label))
for item in [
    bp("CXR") + ": hyperinflation (flattened diaphragm) in chronic asthma; usually normal between attacks; pneumothorax in severe attack",
    bp("Sputum") + ": eosinophils, " + bp("Charcot-Leyden crystals") + ", " + bp("Curschmann's spirals") + " (mucus plugs) - characteristic",
    bp("Blood CBC") + ": eosinophilia (>400/microL)",
    bp("Total IgE and specific IgE/RAST") + ": elevated in atopic asthma",
    bp("ABG") + ": in severe attack - hypoxemia (low PaO2); initially hypocapnia; PaCO2 rising = impending respiratory failure",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Management - Stepwise Approach (GINA Guidelines)"))
step_data = [
    [Paragraph(bp("Step"), body_style), Paragraph(bp("Severity"), body_style), Paragraph(bp("Treatment"), body_style)],
    [Paragraph("Step 1", body_style), Paragraph("Intermittent", body_style),
     Paragraph("SABA (Salbutamol/Albuterol) PRN only - no regular controller needed", body_style)],
    [Paragraph("Step 2", body_style), Paragraph("Mild persistent", body_style),
     Paragraph("Low-dose ICS (Beclomethasone/Budesonide) + SABA PRN", body_style)],
    [Paragraph("Step 3", body_style), Paragraph("Moderate persistent", body_style),
     Paragraph("Low/Medium dose ICS + LABA (Salmeterol/Formoterol) combined inhaler", body_style)],
    [Paragraph("Step 4", body_style), Paragraph("Severe persistent", body_style),
     Paragraph("Medium/High dose ICS + LABA +/- LAMA (Tiotropium) +/- Montelukast", body_style)],
    [Paragraph("Step 5", body_style), Paragraph("Very severe", body_style),
     Paragraph("Oral corticosteroids / Biologic therapy: Omalizumab (anti-IgE, for atopic), Mepolizumab (anti-IL5, eosinophilic)", body_style)],
]
story.append(make_table(step_data, [2.5*cm, 4*cm, 10.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Key Drugs Summary:"), bold_label))
drug_data = [
    [Paragraph(bp("Drug"), body_style), Paragraph(bp("Class"), body_style), Paragraph(bp("Role / Note"), body_style)],
    [Paragraph("Salbutamol", body_style), Paragraph("SABA", body_style),
     Paragraph("Reliever; bronchodilator; first line in acute attack; onset 5 min", body_style)],
    [Paragraph("Salmeterol/Formoterol", body_style), Paragraph("LABA", body_style),
     Paragraph("Controller; never use alone (always with ICS)", body_style)],
    [Paragraph("Beclomethasone/Budesonide/Fluticasone", body_style), Paragraph("ICS", body_style),
     Paragraph("Mainstay prevention; most effective controller; rinse mouth after use to prevent candidiasis", body_style)],
    [Paragraph("Ipratropium", body_style), Paragraph("SAMA", body_style),
     Paragraph("Add-on bronchodilator in severe attack (nebulized)", body_style)],
    [Paragraph("Montelukast/Zafirlukast", body_style), Paragraph("LTRA", body_style),
     Paragraph("Useful in aspirin-sensitive asthma and exercise-induced", body_style)],
    [Paragraph("Theophylline", body_style), Paragraph("Methylxanthine", body_style),
     Paragraph("Add-on; narrow therapeutic index; drug interactions (erythromycin raises levels)", body_style)],
    [Paragraph("Prednisolone", body_style), Paragraph("Oral steroid", body_style),
     Paragraph("Acute severe attack (40-50 mg/day x 5 days) and Step 5 maintenance", body_style)],
    [Paragraph("Omalizumab", body_style), Paragraph("Anti-IgE biologic", body_style),
     Paragraph("SC injection; severe allergic asthma; expensive", body_style)],
]
story.append(make_table(drug_data, [5*cm, 2.7*cm, 9.3*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Management of Acute Severe Asthma / Status Asthmaticus"))
for item in [
    bp("Sit upright") + "; high-flow O2 (40-60%) to maintain SpO2 >94%",
    bp("Nebulized Salbutamol") + " 2.5-5 mg every 20 min x 3, then hourly",
    bp("Add Nebulized Ipratropium") + " 0.5 mg - if not responding to salbutamol",
    bp("IV/Oral Hydrocortisone") + " 200 mg IV stat or Prednisolone 40-50 mg oral",
    bp("IV Magnesium Sulphate") + " 1.2-2 g over 20 min - smooth muscle relaxant (if FEV1 <30% predicted)",
    bp("IV Aminophylline") + " - loading dose for those not already on theophylline",
    bp("NIV / Mechanical ventilation") + " - if deteriorating despite all measures",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    "(1) Always have " + bp("salbutamol inhaler") + " available in the dental clinic - record asthma history. "
    "(2) " + bp("Avoid aspirin / NSAIDs") + " - use paracetamol for analgesia. "
    "(3) Avoid bisulfite-containing local anesthetics (rare but reported trigger). "
    "(4) Stress and anxiety can trigger bronchospasm - anxiolysis/pre-medication may be needed. "
    "(5) " + bp("Erythromycin raises theophylline levels") + " - risk of toxicity; use alternative antibiotic. "
    "(6) Inhaled steroids can cause oral candidiasis - advise rinsing mouth after every dose. "
    "(7) In an acute attack in the dental chair: stop procedure, sit upright, administer salbutamol inhaler (2-4 puffs), call emergency services if no improvement.",
    body_style))

# FOOTER
story.append(Spacer(1, 0.3*cm))
story.append(HRFlowable(width="100%", thickness=1, color=colors.HexColor('#9fa8da')))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(
    "General Medicine Short Notes | BDS 3rd Year | Gujarat University | "
    "Based on Anil K. Tripathi - General Medicine for BDS | Prepared for 7-8 Mark Questions",
    footer_style))

doc.build(story)
print("PDF generated successfully!")
Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes.py

Reading File
Editing File

~/bds-notes/generate_notes.py

Successfully replaced 1 instance(s) of the string in '/tmp/workspace/bds-notes/generate_notes.py'
Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes.py 2>&1

Running Command

ls -lh /tmp/workspace/bds-notes/General_Medicine_Short_Notes_BDS.pdf

Your PDF is ready! Here is the download link:

General Medicine Short Notes BDS

PDF Document · PDF


Here is a summary of what is covered in each topic (all tailored for 7-8 mark Gujarat University BDS 3rd year answers):

TOPIC 1 - SYNCOPE
  • Definition (TLOC due to global cerebral hypoperfusion)
  • Etiology table: Vasovagal (MC), Cardiac, Orthostatic, Situational, Carotid sinus, Neurological
  • Clinical features: prodrome, during episode, post-syncopal (no post-ictal confusion - key difference from seizure)
  • Investigations: ECG, Holter, Echo, Tilt table test
  • Treatment: vasovagal vs cardiac
  • Dental relevance: most common dental emergency, management in dental chair
TOPIC 2 - ARRHYTHMIA
  • Definition + normal sinus rhythm
  • Classification table: by rate, supraventricular, ventricular, conduction defects
  • Key arrhythmias: AF (ECG findings, causes, stroke risk), VT, Complete heart block (Stokes-Adams), Sick sinus syndrome
  • Investigations: ECG, Holter, EPS, Echo
  • Treatment table: rate control, rhythm control, pacemaker, ICD, ablation, anticoagulation
  • Dental relevance: warfarin INR, epinephrine, drug interactions (erythromycin + QT prolongation)
TOPIC 3 - PNEUMONIA
  • Definition
  • Classification: by setting (CAP/HAP/VAP/aspiration), etiology, anatomy
  • Pathology: 4 stages of lobar pneumonia (congestion, red hepatization, grey hepatization, resolution)
  • Clinical features: symptoms + examination findings table
  • Investigations: CXR (air bronchogram), sputum, CBC, ABG
  • CURB-65 severity score
  • Antibiotic therapy by severity + supportive treatment
  • Complications
  • Dental relevance: aspiration pneumonia from oral anaerobes
TOPIC 4 - LUNG ABSCESS
  • Definition (primary vs secondary)
  • Organisms: anaerobes (MC), aerobes
  • Pathways table: aspiration (MC), pneumonia complication, bronchial obstruction, hematogenous
  • Site predilection: right lung, posterior segment RUL
  • Clinical features: acute phase vs drainage phase (foul-smelling sputum, 3-layer sputum - classic)
  • Signs: amphoric breathing, clubbing
  • Investigations: CXR (thick-walled cavity with air-fluid level), CT, bronchoscopy
  • Treatment: Clindamycin (DOC) x 6-8 weeks, postural drainage; surgical indications
  • Complications
  • Dental relevance: dental sepsis as MC predisposing factor
TOPIC 5 - BRONCHIAL ASTHMA
  • Definition (3 components: hyperresponsiveness + reversible obstruction + inflammation)
  • Classification: extrinsic (IgE-mediated), intrinsic, occupational, Samter's triad, exercise-induced
  • Pathophysiology: early phase (mast cell - histamine/LTs) + late phase (eosinophils, remodeling)
  • Classic triad: wheeze + cough + breathlessness
  • Investigations: spirometry (FEV1/FVC <70%, reversibility >12%), PEFR, Curschmann's spirals, eosinophilia, IgE
  • GINA stepwise treatment table (Steps 1-5)
  • Drug table: SABA, LABA, ICS, SAMA, LTRA, theophylline, biologics
  • Acute severe asthma management (nebulized salbutamol, ipratropium, steroids, IV Mg)
  • Dental relevance: 7 specific points (avoid aspirin/NSAIDs, salbutamol on standby, erythromycin-theophylline interaction, oral candidiasis from ICS)

Write me a shrot notes for the following topics from anil k tripathi book of general medicine for bds gujarat university for 3 year exams about 7-8 marks Male concise to the point precise ans to the topics are Chronic obstructive pulmonary disease Cor pulmonale Tuberculosis Pleural disease Pneumothorax In pdf form

Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Writing File

~/bds-notes/generate_notes2.py

from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY

doc = SimpleDocTemplate(
    "/tmp/workspace/bds-notes/General_Medicine_Short_Notes_BDS_Part2.pdf",
    pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2*cm, bottomMargin=2*cm
)

styles = getSampleStyleSheet()

title_style = ParagraphStyle(
    'MainTitle', parent=styles['Title'],
    fontSize=18, textColor=colors.HexColor('#1b5e20'),
    spaceAfter=4, alignment=TA_CENTER, fontName='Helvetica-Bold'
)
subtitle_style = ParagraphStyle(
    'SubTitle', parent=styles['Normal'],
    fontSize=10, textColor=colors.HexColor('#4a4a4a'),
    spaceAfter=12, alignment=TA_CENTER, fontName='Helvetica-Oblique'
)
body_style = ParagraphStyle(
    'Body', parent=styles['Normal'],
    fontSize=9.5, textColor=colors.HexColor('#212121'),
    spaceAfter=3, spaceBefore=1,
    leading=14, alignment=TA_JUSTIFY, fontName='Helvetica'
)
bullet_style = ParagraphStyle(
    'Bullet', parent=styles['Normal'],
    fontSize=9.5, textColor=colors.HexColor('#212121'),
    spaceAfter=2, spaceBefore=1,
    leading=13, leftIndent=14, bulletIndent=4,
    fontName='Helvetica'
)
bold_label = ParagraphStyle(
    'BoldLabel', parent=styles['Normal'],
    fontSize=9.5, textColor=colors.HexColor('#1b5e20'),
    spaceAfter=1, spaceBefore=3,
    fontName='Helvetica-Bold'
)
footer_style = ParagraphStyle(
    'Footer', parent=styles['Normal'],
    fontSize=8, textColor=colors.HexColor('#757575'),
    alignment=TA_CENTER
)

def topic_banner(title, number):
    data = [[Paragraph('<font color="white"><b>TOPIC %s: %s</b></font>' % (number, title),
        ParagraphStyle('banner', fontSize=13, textColor=colors.white,
            fontName='Helvetica-Bold', alignment=TA_LEFT))]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#1b5e20')),
        ('TOPPADDING', (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
    ]))
    return t

def section_box(title):
    data = [[Paragraph('<b>%s</b>' % title,
        ParagraphStyle('sbox', fontSize=10, textColor=colors.HexColor('#1b5e20'),
            fontName='Helvetica-Bold'))]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#e8f5e9')),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 8),
        ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor('#388e3c')),
    ]))
    return t

def make_table(data_list, col_widths):
    t = Table(data_list, colWidths=col_widths)
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8f5e9')),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#81c784')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#f1f8e9')]),
    ]))
    return t

def bp(text):
    return '<b>%s</b>' % text

story = []

# HEADER
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph("GENERAL MEDICINE", title_style))
story.append(Paragraph("Short Notes for BDS 3rd Year | Gujarat University Examinations", subtitle_style))
story.append(Paragraph("Based on Anil K. Tripathi - General Medicine for BDS", ParagraphStyle(
    'ref', fontSize=9, textColor=colors.HexColor('#757575'),
    alignment=TA_CENTER, fontName='Helvetica-Oblique', spaceAfter=4)))
story.append(Paragraph("Each topic: 7-8 Marks | Concise, Precise, Exam-Oriented", ParagraphStyle(
    'info', fontSize=9, textColor=colors.HexColor('#c62828'),
    alignment=TA_CENTER, fontName='Helvetica-Bold', spaceAfter=10)))
story.append(HRFlowable(width="100%", thickness=2, color=colors.HexColor('#1b5e20')))
story.append(Spacer(1, 0.3*cm))

toc_data = [
    [Paragraph(bp("No."), body_style), Paragraph(bp("Topic"), body_style), Paragraph(bp("Marks"), body_style)],
    [Paragraph("1.", body_style), Paragraph("Chronic Obstructive Pulmonary Disease (COPD)", body_style), Paragraph("7-8", body_style)],
    [Paragraph("2.", body_style), Paragraph("Cor Pulmonale", body_style), Paragraph("7-8", body_style)],
    [Paragraph("3.", body_style), Paragraph("Tuberculosis (TB)", body_style), Paragraph("7-8", body_style)],
    [Paragraph("4.", body_style), Paragraph("Pleural Disease (Effusion + Empyema)", body_style), Paragraph("7-8", body_style)],
    [Paragraph("5.", body_style), Paragraph("Pneumothorax", body_style), Paragraph("7-8", body_style)],
]
toc_table = Table(toc_data, colWidths=[1.5*cm, 13*cm, 2.5*cm])
toc_table.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#e8f5e9')),
    ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#81c784')),
    ('ALIGN', (2,0), (2,-1), 'CENTER'),
    ('TOPPADDING', (0,0), (-1,-1), 4),
    ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ('LEFTPADDING', (0,0), (-1,-1), 8),
]))
story.append(toc_table)
story.append(Spacer(1, 0.5*cm))
story.append(PageBreak())

# ============================================================
# TOPIC 1: COPD
# ============================================================
story.append(topic_banner("CHRONIC OBSTRUCTIVE PULMONARY DISEASE (COPD)", "1"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "COPD is a common, preventable, and treatable disease characterized by persistent respiratory symptoms "
    "and airflow limitation that is " + bp("not fully reversible") + ", usually progressive, and associated with "
    "enhanced chronic inflammatory response in the airways and lungs to noxious particles or gases (mainly cigarette smoke). "
    "It includes two major components: " + bp("Emphysema") + " and " + bp("Chronic Bronchitis") + ".",
    body_style))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Components of COPD"))
comp_data = [
    [Paragraph(bp("Component"), body_style), Paragraph(bp("Definition"), body_style), Paragraph(bp("Pathology"), body_style)],
    [Paragraph("Emphysema", body_style),
     Paragraph("Permanent enlargement of air spaces distal to terminal bronchioles due to destruction of alveolar walls", body_style),
     Paragraph("Destruction of alveolar elastic support by neutrophil-derived proteases (elastase). Loss of elastic recoil.", body_style)],
    [Paragraph("Chronic Bronchitis", body_style),
     Paragraph("Persistent productive cough for at least 3 consecutive months in at least 2 consecutive years (clinical definition)", body_style),
     Paragraph("Hypertrophy of mucus glands, goblet cell metaplasia, small airway inflammation (bronchiolitis), bronchiolar fibrosis", body_style)],
]
story.append(make_table(comp_data, [3.5*cm, 6.5*cm, 7*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Etiology / Risk Factors"))
for item in [
    bp("Cigarette smoking") + " - single most important cause (>90% of cases); dose-dependent",
    bp("Alpha-1 antitrypsin (AAT) deficiency") + " - genetic cause; panacinar emphysema predominantly in non-smokers",
    bp("Air pollution") + " - indoor (biomass fuel) and outdoor (PM2.5, sulfur dioxide)",
    bp("Occupational exposure") + " - coal dust, silica, cadmium",
    bp("Recurrent respiratory infections") + " in childhood",
    bp("Asthma-COPD overlap") + " - uncontrolled asthma leading to permanent airflow limitation",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Pathophysiology"))
story.append(Paragraph(
    "Inhaled noxious particles/smoke activate " + bp("macrophages") + " and " + bp("neutrophils") + " in the airways. "
    "Neutrophil elastase and matrix metalloproteinases (MMPs) destroy alveolar walls (emphysema). "
    "Chronic inflammation causes airway wall thickening, mucus hypersecretion, and bronchiolitis. "
    "Result: " + bp("irreversible airflow limitation") + ", air trapping, dynamic hyperinflation, V/Q mismatch, "
    "hypoxemia, and ultimately cor pulmonale.",
    body_style))

story.append(section_box("Classification - GOLD Staging (Spirometry)"))
gold_data = [
    [Paragraph(bp("GOLD Stage"), body_style), Paragraph(bp("FEV1 (post-bronchodilator)"), body_style), Paragraph(bp("Severity"), body_style)],
    [Paragraph("GOLD 1", body_style), Paragraph("FEV1 >= 80% predicted", body_style), Paragraph("Mild", body_style)],
    [Paragraph("GOLD 2", body_style), Paragraph("FEV1 50-79% predicted", body_style), Paragraph("Moderate", body_style)],
    [Paragraph("GOLD 3", body_style), Paragraph("FEV1 30-49% predicted", body_style), Paragraph("Severe", body_style)],
    [Paragraph("GOLD 4", body_style), Paragraph("FEV1 <30% predicted", body_style), Paragraph("Very severe", body_style)],
]
story.append(Paragraph("All stages require: " + bp("FEV1/FVC <0.70") + " post-bronchodilator (confirms airflow limitation)", bold_label))
story.append(make_table(gold_data, [3.5*cm, 8*cm, 5.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Emphysema (Type A - Pink Puffer):"), bold_label))
for item in [
    "Severe breathlessness (dyspnoea) - main complaint",
    "Minimal or no cough",
    bp("Barrel-shaped chest") + " (increased AP diameter), hyperinflation",
    bp("Pursed-lip breathing") + " (to maintain positive expiratory pressure)",
    "Thin, wasted appearance (weight loss)",
    "Normal/near normal PaO2; PaCO2 normal or low",
    "No cyanosis, no polycythemia",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Chronic Bronchitis (Type B - Blue Bloater):"), bold_label))
for item in [
    "Prominent cough with copious purulent sputum",
    "Breathlessness less prominent initially",
    "Cyanosis, polycythemia, peripheral edema (right heart failure)",
    "Repeated exacerbations (acute-on-chronic episodes)",
    "Hypoxemia (low PaO2) + Hypercapnia (raised PaCO2)",
    "Cor pulmonale - RV failure",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs:"), bold_label))
exam_data = [
    [Paragraph(bp("Examination"), body_style), Paragraph(bp("Findings"), body_style)],
    [Paragraph("Inspection", body_style), Paragraph("Barrel chest, accessory muscle use, pursed lip breathing, cyanosis", body_style)],
    [Paragraph("Palpation", body_style), Paragraph("Reduced chest expansion bilaterally; loss of cardiac dullness (hyperinflation)", body_style)],
    [Paragraph("Percussion", body_style), Paragraph("Hyperresonance (emphysema); obliterated cardiac/liver dullness", body_style)],
    [Paragraph("Auscultation", body_style), Paragraph("Reduced breath sounds; prolonged expiration; expiratory wheeze; coarse crackles in bronchitis", body_style)],
]
story.append(make_table(exam_data, [4*cm, 13*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Investigations"))
for item in [
    bp("Spirometry") + " - " + bp("FEV1/FVC <0.70") + " post-bronchodilator (gold standard for diagnosis); FEV1 determines severity",
    bp("Chest X-ray") + " - hyperinflation, flattened diaphragm, increased retrosternal airspace, bullae; tubular heart",
    bp("HRCT Chest") + " - best for detecting and characterizing emphysema",
    bp("ABG") + " - type 1 (hypoxemia alone) or type 2 (hypoxemia + hypercapnia) respiratory failure",
    bp("CBC") + " - polycythemia (secondary erythrocytosis) in chronic hypoxemia",
    bp("Sputum culture") + " - in exacerbations (H. influenzae, S. pneumoniae, Pseudomonas MC)",
    bp("ECG/Echo") + " - right ventricular hypertrophy, pulmonary hypertension (cor pulmonale)",
    bp("AAT level") + " - if COPD in non-smoker <45 years",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment"))
story.append(Paragraph(bp("Non-Pharmacological (Most Important):"), bold_label))
for item in [
    bp("Smoking cessation") + " - single most effective intervention that slows disease progression",
    "Pulmonary rehabilitation - exercise training, breathing techniques",
    bp("Long-term oxygen therapy (LTOT)") + " - if resting PaO2 <55 mmHg or SpO2 <88%; given >15 h/day; only intervention proven to improve survival",
    "Vaccination: annual influenza + pneumococcal vaccine",
    "Nutritional support",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Pharmacological - Stable COPD (Stepwise):"), bold_label))
rx_data = [
    [Paragraph(bp("Step"), body_style), Paragraph(bp("Drug"), body_style), Paragraph(bp("Examples"), body_style)],
    [Paragraph("All patients", body_style), Paragraph("SABA/SAMA (PRN reliever)", body_style),
     Paragraph("Salbutamol (SABA); Ipratropium (SAMA)", body_style)],
    [Paragraph("Mild-Moderate", body_style), Paragraph("LAMA (preferred) or LABA", body_style),
     Paragraph("Tiotropium (LAMA - 1st choice in COPD); Salmeterol, Formoterol (LABA)", body_style)],
    [Paragraph("Severe / Frequent exacerbations", body_style), Paragraph("LAMA + LABA +/- ICS", body_style),
     Paragraph("Triple therapy: Tiotropium + Salmeterol + Fluticasone", body_style)],
    [Paragraph("Add-on options", body_style), Paragraph("Roflumilast, Theophylline", body_style),
     Paragraph("Roflumilast (PDE4 inhibitor) in severe COPD with frequent exacerbations", body_style)],
]
story.append(make_table(rx_data, [4*cm, 5*cm, 8*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Acute Exacerbation of COPD (AECOPD) Management:"), bold_label))
for item in [
    "Controlled oxygen therapy: target SpO2 88-92% (avoid high flow - hypercapnic drive)",
    "Nebulized Salbutamol + Ipratropium",
    "Systemic Corticosteroids: Prednisolone 30-40 mg/day x 5 days",
    "Antibiotics if purulent sputum / infection: Amoxicillin / Doxycycline / Co-amoxiclav",
    "NIV (BiPAP) if type 2 respiratory failure (pH <7.35 with hypercapnia)",
    "Intubation/IMV as last resort",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Surgical:"), bold_label))
for item in [
    bp("Lung Volume Reduction Surgery (LVRS)") + " - in severe emphysema; improves FEV1 and quality of life",
    bp("Lung transplantation") + " - end-stage COPD",
    bp("Bullectomy") + " - giant bullae causing compression",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    "(1) Use " + bp("caution with sedation and GA") + " - hypercapnic respiratory drive may be suppressed. "
    "(2) Avoid high-flow nasal oxygen (SpO2 target 88-92%). "
    "(3) " + bp("Erythromycin raises theophylline levels") + " - use amoxicillin or doxycycline instead. "
    "(4) Patients on ICS may have oral candidiasis. "
    "(5) NSAIDs may worsen respiratory function in overlap with asthma.",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 2: COR PULMONALE
# ============================================================
story.append(topic_banner("COR PULMONALE", "2"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Cor pulmonale is defined as " + bp("right ventricular hypertrophy, dilation, and dysfunction") +
    " resulting from pulmonary hypertension caused by disorders of the " +
    bp("lung parenchyma, pulmonary vasculature, or chest wall") + " (NOT from left heart disease or congenital heart disease). "
    "It may be " + bp("acute") + " (e.g., massive pulmonary embolism) or " + bp("chronic") + " (e.g., COPD, fibrosis).",
    body_style))

story.append(section_box("Etiology - Causes of Pulmonary Hypertension Leading to Cor Pulmonale"))
etio_data = [
    [Paragraph(bp("Category"), body_style), Paragraph(bp("Conditions"), body_style)],
    [Paragraph("Lung Parenchymal\n(Most Common)", body_style),
     Paragraph("COPD (emphysema/chronic bronchitis) - MC cause of chronic cor pulmonale; "
               "Pulmonary fibrosis, bronchiectasis, severe pneumoconiosis", body_style)],
    [Paragraph("Pulmonary Vascular", body_style),
     Paragraph("Recurrent pulmonary thrombo-embolism (MC cause of ACUTE cor pulmonale), "
               "Primary pulmonary arterial hypertension, Vasculitis", body_style)],
    [Paragraph("Chest Wall / Neuromuscular", body_style),
     Paragraph("Kyphoscoliosis, obesity hypoventilation syndrome (Pickwickian), "
               "Obstructive sleep apnea (OSA), neuromuscular diseases", body_style)],
    [Paragraph("Hypoxia at Altitude", body_style),
     Paragraph("High altitude chronic mountain sickness - hypoxic pulmonary vasoconstriction", body_style)],
]
story.append(make_table(etio_data, [5*cm, 12*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Pathophysiology"))
story.append(Paragraph(
    bp("Key mechanism") + ": Chronic hypoxia (low PaO2) -> "
    bp("hypoxic pulmonary vasoconstriction") + " (HPV) -> pulmonary artery hypertension (PAH) -> "
    "increased right ventricular afterload -> RV hypertrophy (compensated) -> "
    bp("RV dilation and failure") + " (decompensated) -> tricuspid regurgitation, "
    "systemic venous hypertension, edema, ascites, hepatomegaly.",
    body_style))
story.append(Paragraph(
    bp("Additional mechanisms") + ": Destruction of alveolar capillary bed (emphysema) reduces vascular cross-section; "
    "hypercapnia and acidosis aggravate vasoconstriction; polycythemia increases blood viscosity.",
    body_style))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Symptoms:"), bold_label))
for item in [
    "Breathlessness (dyspnoea) - progressive; related to underlying lung disease",
    "Fatigue, exertional limitation",
    bp("Ankle edema") + " and leg swelling (bilateral pitting edema)",
    "Symptoms of underlying lung disease (cough, wheeze, sputum)",
    "Headache, drowsiness (CO2 retention in hypercapnic patients)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs:"), bold_label))
signs_data = [
    [Paragraph(bp("Sign"), body_style), Paragraph(bp("Significance"), body_style)],
    [Paragraph("Raised JVP", body_style), Paragraph("Right ventricular failure / elevated right atrial pressure", body_style)],
    [Paragraph("Prominent 'a' wave in JVP", body_style), Paragraph("RV hypertrophy / tricuspid stenosis", body_style)],
    [Paragraph("Parasternal heave", body_style), Paragraph("Right ventricular hypertrophy (left parasternal lift)", body_style)],
    [Paragraph("Loud P2 (pulmonic S2)", body_style), Paragraph("Pulmonary hypertension", body_style)],
    [Paragraph("Tricuspid regurgitation murmur", body_style), Paragraph("Pansystolic at left sternal edge; increases on inspiration (Carvallo's sign)", body_style)],
    [Paragraph("Hepatomegaly + pulsatile liver", body_style), Paragraph("Passive hepatic congestion; TR causing pulsation", body_style)],
    [Paragraph("Bilateral pitting pedal edema", body_style), Paragraph("Right heart failure", body_style)],
    [Paragraph("Ascites", body_style), Paragraph("Severe, prolonged right heart failure", body_style)],
    [Paragraph("Cyanosis", body_style), Paragraph("Peripheral (cold) and central (V/Q mismatch)", body_style)],
]
story.append(make_table(signs_data, [5.5*cm, 11.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Investigations"))
for item in [
    bp("ECG") + " - P pulmonale (tall peaked P wave >2.5 mm in II, III, aVF = right atrial hypertrophy); "
    "right axis deviation; RV hypertrophy pattern (R>S in V1); S1Q3T3 pattern (acute PE)",
    bp("Chest X-ray") + " - cardiomegaly (right-sided), prominent pulmonary arteries, oligemic peripheral lung fields; "
    "features of underlying lung disease",
    bp("Echocardiography (Echo)") + " - most useful investigation; shows RV dilation/hypertrophy, "
    "estimates pulmonary artery systolic pressure via Doppler; TR present",
    bp("ABG") + " - hypoxemia + hypercapnia (type 2 respiratory failure)",
    bp("CBC") + " - polycythemia (secondary erythrocytosis due to chronic hypoxia)",
    bp("RFT / LFT") + " - renal/hepatic dysfunction secondary to poor perfusion",
    bp("NT-proBNP / BNP") + " - elevated due to right ventricular wall stress",
    bp("Right heart catheterization") + " - gold standard: confirms pulmonary artery pressure (PAP >25 mmHg at rest)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment"))
story.append(Paragraph(bp("Treat Underlying Cause (Most Important):"), bold_label))
for item in [
    "COPD: bronchodilators, smoking cessation, pulmonary rehabilitation",
    "Pulmonary embolism: anticoagulation, thrombolysis",
    "Sleep apnea: CPAP/BiPAP",
    "Kyphoscoliosis: ventilatory support",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Specific Management:"), bold_label))
treat_data = [
    [Paragraph(bp("Treatment"), body_style), Paragraph(bp("Details"), body_style)],
    [Paragraph("Long-term Oxygen Therapy (LTOT)", body_style),
     Paragraph("Primary treatment; corrects hypoxia and reverses pulmonary vasoconstriction; "
               "target PaO2 >60 mmHg / SpO2 >90%; given >15 h/day; ONLY treatment proven to improve survival", body_style)],
    [Paragraph("Diuretics", body_style),
     Paragraph("Furosemide (frusemide) for edema/fluid overload; use cautiously (risk of metabolic alkalosis worsening hypercapnia)", body_style)],
    [Paragraph("Anticoagulation", body_style),
     Paragraph("If pulmonary thromboembolism is the cause; warfarin or NOAC", body_style)],
    [Paragraph("Phlebotomy", body_style),
     Paragraph("If severe polycythemia (PCV >55%) causing hyperviscosity symptoms", body_style)],
    [Paragraph("Pulmonary Vasodilators", body_style),
     Paragraph("Sildenafil (PDE5 inhibitor), Bosentan (endothelin antagonist) - in primary PAH; cautious use in COPD-related cor pulmonale", body_style)],
    [Paragraph("Digoxin", body_style),
     Paragraph("Limited role; only if concurrent LV failure or AF; risk of toxicity in hypoxia", body_style)],
    [Paragraph("Lung Transplantation", body_style),
     Paragraph("End-stage disease unresponsive to medical therapy", body_style)],
]
story.append(make_table(treat_data, [4.5*cm, 12.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Prognosis:"), bold_label))
story.append(Paragraph(
    "Poor once established. If PAP >25 mmHg, 5-year survival is reduced by 50%. "
    "LTOT is the only intervention shown to improve survival in COPD-related cor pulmonale.",
    body_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    "Patients with cor pulmonale are at high cardiovascular risk. "
    bp("Avoid GA") + " or heavy sedation. Dental treatment best done in semi-reclined (not fully supine) position. "
    "Avoid high-dose epinephrine - causes pulmonary vasoconstriction and tachycardia. "
    "Patients on diuretics and digoxin need drug interaction monitoring.",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 3: TUBERCULOSIS
# ============================================================
story.append(topic_banner("TUBERCULOSIS (TB)", "3"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Tuberculosis is a chronic granulomatous infectious disease caused by " +
    bp("Mycobacterium tuberculosis") + " (Koch's bacillus). "
    "It primarily affects the lungs (pulmonary TB) but can affect any organ (extrapulmonary TB). "
    "It is an " + bp("acid-fast bacillus (AFB)") + " - gram positive, non-motile, obligate aerobe, "
    "slow-growing (18-24 hour doubling time).",
    body_style))

story.append(section_box("Epidemiology"))
for item in [
    "India has the highest burden of TB globally (26% of world's TB cases - WHO 2023)",
    "Spread by " + bp("airborne droplet nuclei") + " (1-5 microns); produced by coughing, sneezing, talking",
    "Risk factors: poverty, malnutrition, HIV, DM, immunosuppression, overcrowding, silicosis, alcoholism",
    bp("HIV co-infection") + " is the strongest risk factor for progression from latent to active TB",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Pathogenesis"))
story.append(Paragraph(bp("Primary Tuberculosis (Ghon Complex):"), bold_label))
for item in [
    "Inhaled bacilli reach lower lobes / alveoli - phagocytosed by alveolar macrophages",
    "Bacteria multiply within macrophages",
    "Sensitization develops (4-8 weeks) - T cell mediated immunity",
    bp("Ghon focus") + ": subpleural caseous granuloma (primary focus) + ipsilateral hilar lymphadenopathy",
    "In most immunocompetent individuals: lesion heals, bacilli remain dormant (" + bp("latent TB") + ")",
    "Ranke complex = calcified Ghon focus + calcified hilar nodes",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Post-Primary / Reactivation Tuberculosis:"), bold_label))
for item in [
    "Reactivation of latent bacilli when immunity wanes",
    "Typically affects " + bp("upper lobes") + " (posterior segment - high oxygen tension favors bacilli)",
    "Granulomas undergo central caseation - liquefaction - cavity formation",
    "Spreads via bronchi (endobronchial spread), hematogenous (miliary TB), lymphatics",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Classification"))
class_data = [
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Features"), body_style)],
    [Paragraph("Pulmonary TB\n(Most Common)", body_style),
     Paragraph("Upper lobe involvement with cavitation. Main forms: primary progressive, reactivation (post-primary)", body_style)],
    [Paragraph("Miliary TB", body_style),
     Paragraph("Hematogenous dissemination; 'millet seed' shadows on CXR; affects liver, spleen, meninges, kidneys", body_style)],
    [Paragraph("Extrapulmonary TB", body_style),
     Paragraph("Lymph node TB (scrofula - MC extrapulmonary site), pleural, pericardial, meningeal (TBM), "
               "genitourinary, spinal (Pott's disease), peritoneal", body_style)],
    [Paragraph("Latent TB Infection (LTBI)", body_style),
     Paragraph("Positive TST/IGRA but no symptoms, no active disease, not infectious; may reactivate", body_style)],
    [Paragraph("Drug-Resistant TB", body_style),
     Paragraph("MDR-TB: resistant to Isoniazid + Rifampicin. XDR-TB: additionally resistant to fluoroquinolones + injectables", body_style)],
]
story.append(make_table(class_data, [4*cm, 13*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Constitutional symptoms (B symptoms):"), bold_label))
for item in [
    bp("Fever") + " - low grade, afternoon rise (evening pyrexia), remittent",
    bp("Night sweats") + " (drenching, classical symptom)",
    bp("Weight loss") + " and loss of appetite (anorexia)",
    "Fatigue and weakness",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Respiratory Symptoms:"), bold_label))
for item in [
    bp("Cough") + " - persistent, >3 weeks; initially dry, then productive",
    bp("Hemoptysis") + " - frank blood-tinged sputum; in advanced/cavitatory disease",
    "Breathlessness - with extensive disease or effusion",
    "Pleuritic chest pain - with pleural involvement",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs:"), bold_label))
for item in [
    "Post-tussive crackles (rales) in upper zones - elicited after coughing",
    bp("Amphoric breathing") + " - over a large cavity (hollow sound)",
    "Signs of consolidation, pleural effusion, or fibrosis in chronic cases",
    "Cervical lymphadenopathy (scrofula)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Investigations"))
invest_data = [
    [Paragraph(bp("Investigation"), body_style), Paragraph(bp("Details"), body_style)],
    [Paragraph("Sputum Microscopy\n(Ziehl-Neelsen stain)", body_style),
     Paragraph("AFB (red rods) on ZN stain. At least 3 samples needed (early morning). Sensitivity 60-70%; Cheap, quick, widely available. Most important initial test.", body_style)],
    [Paragraph("Sputum Culture\n(LJ medium)", body_style),
     Paragraph("Gold standard for diagnosis and drug sensitivity. Takes 4-8 weeks for solid media; MGIT broth (2-3 weeks). Sensitivity ~80-85%.", body_style)],
    [Paragraph("Chest X-ray", body_style),
     Paragraph("Upper lobe infiltrates, cavitation, fibrosis, calcification. 'Simon's foci' = old healed apical lesions. Miliary pattern (1-2 mm nodules throughout both lungs).", body_style)],
    [Paragraph("Mantoux Test\n(Tuberculin Skin Test)", body_style),
     Paragraph("5 TU (2 TU in India) of PPD injected intradermally. Read at 48-72h. Positive: induration >=10 mm (>=5 mm in HIV/immunocompromised). Indicates infection, NOT active disease.", body_style)],
    [Paragraph("IGRA (Interferon-Gamma Release Assay)", body_style),
     Paragraph("QuantiFERON-TB Gold; more specific than TST; not affected by BCG vaccination; used for LTBI diagnosis.", body_style)],
    [Paragraph("GeneXpert MTB/RIF\n(CBNAAT)", body_style),
     Paragraph("WHO-endorsed rapid molecular test. Detects M. tuberculosis DNA and rifampicin resistance within 2 hours. High sensitivity (88%) and specificity (98%). India: NIKSHAY program.", body_style)],
    [Paragraph("CT Chest / HRCT", body_style),
     Paragraph("Better than CXR for extent of disease, cavitation, lymphadenopathy, miliary TB.", body_style)],
    [Paragraph("Pleural fluid analysis", body_style),
     Paragraph("Lymphocytic exudate; ADA (adenosine deaminase) >40 IU/L strongly suggests TB pleuritis.", body_style)],
]
story.append(make_table(invest_data, [4.5*cm, 12.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Treatment - RNTCP/WHO Regimen (Drug-Sensitive TB)"))
story.append(Paragraph(
    "First-line drugs: " + bp("R") + "ifampicin (R) | " + bp("I") + "soniazid (H) | " +
    bp("P") + "yrazinamide (Z) | " + bp("E") + "thambutol (E) | [Streptomycin (S) - injectable]",
    body_style))
story.append(Spacer(1, 0.1*cm))

regimen_data = [
    [Paragraph(bp("Category"), body_style), Paragraph(bp("Regimen"), body_style), Paragraph(bp("Duration"), body_style)],
    [Paragraph("New Pulmonary TB", body_style),
     Paragraph("Intensive phase: 2HRZE (Isoniazid + Rifampicin + Pyrazinamide + Ethambutol)", body_style),
     Paragraph("2 months", body_style)],
    [Paragraph("", body_style),
     Paragraph("Continuation phase: 4HR (Isoniazid + Rifampicin)", body_style),
     Paragraph("4 months", body_style)],
    [Paragraph("TB Meningitis / Bone TB", body_style),
     Paragraph("2HRZE + 10HR (continuation phase extended)", body_style),
     Paragraph("12 months total", body_style)],
    [Paragraph("MDR-TB", body_style),
     Paragraph("Bedaquiline + Pretomanid + Linezolid (BPaL) regimen OR individualized based on DST", body_style),
     Paragraph("6-20 months", body_style)],
]
story.append(make_table(regimen_data, [4.5*cm, 8.5*cm, 4*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Key Drug Side Effects:"), bold_label))
se_data = [
    [Paragraph(bp("Drug"), body_style), Paragraph(bp("Major Side Effects"), body_style)],
    [Paragraph("Isoniazid (INH)", body_style),
     Paragraph("Peripheral neuropathy (prevented by Pyridoxine/Vit B6), hepatotoxicity, lupus-like syndrome", body_style)],
    [Paragraph("Rifampicin", body_style),
     Paragraph("Orange/red discoloration of urine/tears/sweat (warn patient!), hepatotoxicity, enzyme inducer (reduces OCP efficacy)", body_style)],
    [Paragraph("Pyrazinamide", body_style),
     Paragraph("Hyperuricemia (gout), hepatotoxicity, arthralgia", body_style)],
    [Paragraph("Ethambutol", body_style),
     Paragraph("Optic neuritis - color blindness (red-green), reduced visual acuity (dose-dependent, reversible)", body_style)],
]
story.append(make_table(se_data, [3.5*cm, 13.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    bp("Active TB is a contraindication to elective dental treatment") + " until patient is non-infectious "
    "(minimum 2 weeks of therapy, 3 AFB-negative sputum smears). "
    "Wear " + bp("N95 mask") + " when treating TB patients; use negative pressure room. "
    bp("Rifampicin") + " is a potent CYP450 enzyme inducer - reduces effectiveness of many drugs including antifungals (fluconazole), "
    "analgesics, and corticosteroids. Isoniazid inhibits metabolism of carbamazepine (risk of toxicity). "
    "Oral lesions: TB ulcer (indurated, painful - usually tongue/palate), lupus vulgaris (skin/face).",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 4: PLEURAL DISEASE
# ============================================================
story.append(topic_banner("PLEURAL DISEASE (Pleural Effusion and Empyema)", "4"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Pleural Effusion - Definition"))
story.append(Paragraph(
    "Pleural effusion is defined as an abnormal accumulation of fluid in the pleural space (normally <15 mL). "
    "Fluid accumulates when production exceeds absorption. Classified as " +
    bp("transudate") + " (protein <30 g/L) or " + bp("exudate") + " (protein >30 g/L) using " +
    bp("Light's criteria") + ".",
    body_style))

story.append(section_box("Light's Criteria (Exudate if ANY one met)"))
light_data = [
    [Paragraph(bp("Criterion"), body_style), Paragraph(bp("Threshold"), body_style)],
    [Paragraph("Pleural fluid protein / Serum protein ratio", body_style), Paragraph("> 0.5", body_style)],
    [Paragraph("Pleural fluid LDH / Serum LDH ratio", body_style), Paragraph("> 0.6", body_style)],
    [Paragraph("Pleural fluid LDH", body_style), Paragraph("> 2/3 of upper limit of normal serum LDH", body_style)],
]
story.append(make_table(light_data, [10*cm, 7*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Etiology - Transudate vs Exudate"))
tve_data = [
    [Paragraph(bp("TRANSUDATE"), body_style), Paragraph(bp("EXUDATE"), body_style)],
    [Paragraph("Congestive cardiac failure (CCF) - MC overall cause\nNephrotic syndrome\nLiver cirrhosis (hepatic hydrothorax)\nHypoalbuminemia (malnutrition)\nHypothyroidism", body_style),
     Paragraph("Pneumonia / Para-pneumonic effusion - MC exudative cause\nTuberculosis - MC exudate in developing countries\nMalignancy (lung, breast, mesothelioma)\nPulmonary embolism\nSubphrenic abscess\nRheumatoid / SLE\nPancreatitis (left-sided)", body_style)],
]
story.append(make_table(tve_data, [8.5*cm, 8.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Symptoms:"), bold_label))
for item in [
    "Breathlessness (dyspnoea) - proportional to volume; main symptom",
    "Pleuritic chest pain - sharp, worse on breathing (pleuritis); may be absent when effusion large",
    "Dry cough",
    "Features of underlying disease (fever in infection/TB; weight loss in malignancy)",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs (Classical):"), bold_label))
signs2_data = [
    [Paragraph(bp("Sign"), body_style), Paragraph(bp("Description"), body_style)],
    [Paragraph("Inspection", body_style), Paragraph("Fullness of intercostal spaces on affected side; reduced chest movement", body_style)],
    [Paragraph("Tracheal deviation", body_style), Paragraph("Away from the effusion if massive (>1000 mL); toward if with collapse", body_style)],
    [Paragraph("Palpation", body_style), Paragraph("Reduced chest expansion; decreased tactile vocal fremitus / VF (fluid damps vibrations)", body_style)],
    [Paragraph("Percussion", body_style), Paragraph(bp("Stony dull") + " - the most characteristic sign (dullest note in medicine)", body_style)],
    [Paragraph("Auscultation", body_style), Paragraph("Absent breath sounds; reduced VR; " + bp("Aegophony") + " (bleating quality) at fluid upper level; bronchial breathing above fluid", body_style)],
]
story.append(make_table(signs2_data, [4*cm, 13*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Investigations"))
for item in [
    bp("Chest X-ray (PA)") + " - blunting of costophrenic angle (>200 mL); homogeneous opacity with curved (concave meniscus) upper border; "
    "trachea deviated away if large; supine CXR may show only diffuse haze (layering)",
    bp("Ultrasound chest") + " - detects even small effusions (>100 mL); guides thoracocentesis (reduces complications); detects loculations",
    bp("CT chest") + " - defines extent; distinguishes effusion from consolidation; detects underlying malignancy, empyema",
    bp("Diagnostic thoracocentesis (pleural tap)") + " - " + bp("most important investigation") + "; aspirate 30-50 mL for analysis",
    bp("Pleural fluid analysis") + ": protein, LDH (Light's criteria), glucose, pH, cytology (malignant cells), "
    "culture (bacteria + AFB), ADA (>40 IU/L = TB), triglycerides (chylothorax)",
    bp("Pleural biopsy") + " - closed/Abrams needle or CT-guided/VATS; for TB and malignancy",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Treatment of Pleural Effusion"))
for item in [
    bp("Treat underlying cause") + ": diuretics for CCF; antibiotics for infection; anti-TB drugs for TB",
    bp("Therapeutic thoracocentesis") + ": drain not more than 1.5 L at one time (risk of re-expansion pulmonary edema)",
    bp("Intercostal drain (ICD) / chest tube") + ": for large symptomatic effusions, empyema, malignant effusions",
    bp("Pleurodesis") + ": talc/chemical pleurodesis via ICD for recurrent malignant effusions; prevents re-accumulation",
    bp("VATS (Video-Assisted Thoracoscopic Surgery)") + ": for loculated/non-draining effusions; allows direct visualization and biopsy",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Empyema Thoracis"))
story.append(Paragraph(
    bp("Definition") + ": Frank pus in the pleural space. "
    "Stages: (1) " + bp("Exudative") + " (free-flowing thin fluid), "
    "(2) " + bp("Fibrinopurulent") + " (thick turbid fluid, fibrin deposits, loculations), "
    "(3) " + bp("Organizing") + " (fibrous cortex/peel over lung).",
    body_style))

story.append(Paragraph(bp("Causes:"), bold_label))
for item in [
    "Para-pneumonic (complication of pneumonia) - MC cause",
    "Post-surgical / Post-traumatic",
    "Rupture of lung abscess into pleural space",
    "Subphrenic abscess (trans-diaphragmatic spread)",
    "Esophageal perforation",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Diagnosis:"), bold_label))
story.append(Paragraph(
    "Suspected when pleural fluid is: " + bp("pH <7.2") + ", glucose <2.2 mmol/L, LDH >1000 IU/L, positive Gram stain/culture, or frank pus on aspiration.",
    body_style))

story.append(Paragraph(bp("Treatment:"), bold_label))
for item in [
    "IV antibiotics (broad spectrum - covering anaerobes: Piperacillin-tazobactam + Metronidazole)",
    bp("Urgent intercostal drainage (ICD)") + " - definitive management; large bore drain",
    "Intrapleural fibrinolytics (streptokinase/urokinase or tPA+DNase) for loculated empyema",
    bp("Surgical decortication (VATS or open)") + " - stage III empyema with organizing fibrous peel",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    "Dental infections (Ludwig's angina, deep space infections) can rarely spread to mediastinum and pleural space causing empyema. "
    "Patients with pleural effusion have impaired respiratory reserve - "
    "ensure optimal positioning (semi-upright) and limit LA volume and sedation.",
    body_style))

story.append(PageBreak())

# ============================================================
# TOPIC 5: PNEUMOTHORAX
# ============================================================
story.append(topic_banner("PNEUMOTHORAX", "5"))
story.append(Spacer(1, 0.2*cm))

story.append(section_box("Definition"))
story.append(Paragraph(
    "Pneumothorax is the presence of " + bp("air in the pleural space") + ", causing lung collapse. "
    "It disrupts the negative intrapleural pressure, allowing the lung to recoil and collapse. "
    "May range from a small rim of air to complete lung collapse with mediastinal shift.",
    body_style))

story.append(section_box("Classification / Types"))
types_data = [
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Description"), body_style), Paragraph(bp("Features"), body_style)],
    [Paragraph("Spontaneous\nPrimary (PSP)", body_style),
     Paragraph("No underlying lung disease; rupture of subpleural blebs/bullae", body_style),
     Paragraph("Young, tall, thin males; smokers; M:F = 6:1; recurrence rate 50%. Usually right-sided.", body_style)],
    [Paragraph("Spontaneous\nSecondary (SSP)", body_style),
     Paragraph("Complicates existing lung disease", body_style),
     Paragraph("COPD (MC cause), asthma, TB, Pneumocystis pneumonia, cystic fibrosis, Marfan syndrome, malignancy. Older patients, more serious.", body_style)],
    [Paragraph("Traumatic", body_style),
     Paragraph("Due to penetrating or blunt chest trauma", body_style),
     Paragraph("Rib fractures, penetrating wounds, iatrogenic (subclavian line, mechanical ventilation, thoracocentesis, CPR)", body_style)],
    [Paragraph("Tension\nPneumothorax", body_style),
     Paragraph("Life-threatening; air enters pleural space but cannot escape (one-way valve)", body_style),
     Paragraph("Progressive pressure rise, mediastinal shift away, compression of heart/great vessels, cardiovascular collapse. EMERGENCY.", body_style)],
]
story.append(make_table(types_data, [3.5*cm, 5*cm, 8.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(section_box("Clinical Features"))
story.append(Paragraph(bp("Symptoms:"), bold_label))
for item in [
    bp("Sudden onset") + " unilateral pleuritic chest pain - sharp, stabbing",
    bp("Breathlessness") + " (dyspnoea) - may be minimal in PSP but severe in SSP and tension",
    "Dry cough",
    "In large/tension pneumothorax: severe respiratory distress, cyanosis, cardiovascular compromise",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Physical Signs:"), bold_label))
psigns_data = [
    [Paragraph(bp("Sign"), body_style), Paragraph(bp("Pneumothorax"), body_style)],
    [Paragraph("Tracheal position", body_style), Paragraph("Central (small) or deviated TOWARD affected side (in collapse). In TENSION: deviated AWAY from affected side.", body_style)],
    [Paragraph("Chest movement", body_style), Paragraph("Reduced on affected side", body_style)],
    [Paragraph("Palpation - VF/TVF", body_style), Paragraph("Decreased / absent on affected side (air dampens transmission)", body_style)],
    [Paragraph("Percussion", body_style), Paragraph(bp("Hyperresonant") + " (tympanic) on affected side - key distinguishing sign", body_style)],
    [Paragraph("Auscultation", body_style), Paragraph("Absent / markedly reduced breath sounds on affected side", body_style)],
]
story.append(make_table(psigns_data, [4.5*cm, 12.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("Tension Pneumothorax - Classical Signs (EMERGENCY):"), bold_label))
for item in [
    "Severe respiratory distress + hypoxia",
    bp("Tracheal deviation AWAY from affected side"),
    "Absent breath sounds + hyperresonance on affected side",
    "Raised JVP (impaired venous return)",
    "Hypotension + tachycardia (cardiogenic shock)",
    "Cyanosis",
    bp("Do NOT wait for X-ray if tension pneumothorax suspected") + " - immediate needle decompression",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Investigations"))
for item in [
    bp("Chest X-ray (CXR)") + " - " + bp("investigation of choice") + "; shows: absence of lung markings beyond the visceral pleura edge, "
    "visible pleural line (white line), collapsed lung margin, mediastinal shift (tension). "
    "Expiratory film enhances small pneumothorax detection.",
    bp("CT Chest") + " - most accurate; quantifies size precisely; detects blebs/bullae; differentiates from bulla (mistaken for pneumothorax)",
    bp("Ultrasound") + " - 'lung sliding' absent in pneumothorax; quick bedside diagnosis; useful in trauma bay",
    bp("ABG") + " - hypoxemia; hypocapnia initially; hypercapnia in severe cases",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(section_box("Management"))
story.append(Paragraph(bp("Size Assessment:"), bold_label))
story.append(Paragraph(
    "British Thoracic Society (BTS): Small = rim of air <2 cm; Large = rim of air >=2 cm "
    "(measured at level of hilum). American College of Chest Physicians (ACCP): Small <3 cm apex-to-cupola.",
    body_style))

mgmt_data = [
    [Paragraph(bp("Type / Size"), body_style), Paragraph(bp("Management"), body_style)],
    [Paragraph("PSP - Small (<2 cm)\nMinimal symptoms", body_style),
     Paragraph("Observation + high-flow O2 (100% - accelerates reabsorption x4 times); "
               "discharge with review in 2-4 weeks if stable", body_style)],
    [Paragraph("PSP - Large (>=2 cm)\nor symptomatic", body_style),
     Paragraph(bp("Aspiration") + " with 16G Venflon at 2nd ICS midclavicular line; "
               "if successful (lung re-expands) discharge with follow-up", body_style)],
    [Paragraph("SSP (all sizes)", body_style),
     Paragraph(bp("Intercostal drain (ICD)") + " insertion - connected to underwater seal "
               "(2nd ICS MCL or 5th ICS anterior axillary line - 'safe triangle'). All secondary pneumothoraces need admission.", body_style)],
    [Paragraph("Tension Pneumothorax\n(EMERGENCY)", body_style),
     Paragraph(bp("IMMEDIATE") + ": Large-bore needle (14G cannula) at 2nd ICS MCL - emergency decompression. "
               "Followed by ICD insertion. Do NOT delay for investigations.", body_style)],
    [Paragraph("Persistent air leak\n(>5 days)", body_style),
     Paragraph("VATS with surgical bullectomy + pleurodesis (abrasion/talc). "
               "Success rate >95% for preventing recurrence.", body_style)],
    [Paragraph("Recurrent PSP", body_style),
     Paragraph(bp("Pleurodesis") + ": talc (insufflation via VATS) or chemical (tetracycline/bleomycin via ICD). "
               "Prevents ipsilateral recurrence.", body_style)],
]
story.append(make_table(mgmt_data, [4.5*cm, 12.5*cm]))
story.append(Spacer(1, 0.1*cm))

story.append(Paragraph(bp("High-Flow O2 in Pneumothorax:"), bold_label))
story.append(Paragraph(
    "Breathing 100% O2 via non-rebreather mask " + bp("accelerates pleural air absorption 4-fold") +
    " by creating an inert gas pressure gradient. Used as definitive treatment in small PSP "
    "and as adjunct during observation.",
    body_style))

story.append(Paragraph(bp("Complications:"), bold_label))
for item in [
    bp("Tension pneumothorax") + " - life-threatening; mediastinal shift, cardiac compression",
    "Haemopneumothorax - blood + air in pleural space",
    bp("Re-expansion pulmonary edema") + " - if large pneumothorax drained too rapidly",
    "Chronic/persistent pneumothorax",
    "Empyema (after ICD insertion)",
    bp("Recurrence") + " - PSP: 50% risk; SSP: even higher",
]:
    story.append(Paragraph("- %s" % item, bullet_style))

story.append(Paragraph(bp("Dental Relevance:"), bold_label))
story.append(Paragraph(
    "(1) " + bp("N2O (nitrous oxide) is contraindicated") + " in patients with known pneumothorax - "
    "N2O diffuses into the air-containing cavity 34x faster than nitrogen exits, rapidly expanding the pneumothorax. "
    "(2) Avoid " + bp("positive pressure ventilation") + " in patients with COPD or blebs - risk of barotrauma. "
    "(3) Patients who have had a recent pneumothorax should NOT receive GA or N2O until fully resolved and reviewed. "
    "(4) Marfan syndrome patients (tall, thin) at higher risk - check before elective procedures.",
    body_style))

# FOOTER
story.append(Spacer(1, 0.3*cm))
story.append(HRFlowable(width="100%", thickness=1, color=colors.HexColor('#81c784')))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(
    "General Medicine Short Notes | BDS 3rd Year | Gujarat University | "
    "Based on Anil K. Tripathi - General Medicine for BDS | Prepared for 7-8 Mark Questions",
    footer_style))

doc.build(story)
print("PDF generated successfully!")
Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes2.py 2>&1

Reading File
Editing File

~/bds-notes/generate_notes2.py

Successfully replaced 1 instance(s) of the string in '/tmp/workspace/bds-notes/generate_notes2.py'
Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes2.py 2>&1

Reading File
Editing File

~/bds-notes/generate_notes2.py

Successfully replaced 1 instance(s) of the string in '/tmp/workspace/bds-notes/generate_notes2.py'
Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes2.py 2>&1

Running Command

cd /tmp/workspace/bds-notes && python3 -c " import ast, sys with open('generate_notes2.py','r') as f: src = f.read() # Find all lines that are continuations starting with bp( without + at start - they need + before them lines = src.split('\n') fixed = [] for i, line in enumerate(lines): stripped = line.lstrip() # If a line starts with bp( and prev line ends with a string literal (quote) without + at end if stripped.startswith('bp(') and i>0: prev = lines[i-1].rstrip() if prev.endswith('\"') or prev.endswith(\"'\"): line = line[:len(line)-len(stripped)] + '+ ' + stripped fixed.append(line) result = '\n'.join(fixed) with open('generate_notes2_fixed.py','w') as f: f.write(result) print('Done') " 2>&1

Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes2_fixed.py 2>&1

Running Command

ls -lh /tmp/workspace/bds-notes/General_Medicine_Short_Notes_BDS_Part2.pdf

Your PDF is ready! Download it here:

General Medicine Short Notes BDS Part2

PDF Document · PDF


Here is a summary of what is covered in each topic:

TOPIC 1 - COPD
  • Definition (not fully reversible airflow limitation)
  • Components table: Emphysema vs Chronic Bronchitis (definition + pathology)
  • Etiology: smoking (MC), AAT deficiency, pollution, occupational
  • Pathophysiology: neutrophil elastase, airflow limitation, V/Q mismatch, cor pulmonale
  • GOLD staging table (1-4 based on FEV1)
  • Classic clinical types: Pink Puffer (emphysema) vs Blue Bloater (chronic bronchitis)
  • Physical examination findings table
  • Investigations: spirometry (FEV1/FVC <0.70), CXR, HRCT, ABG, CBC
  • Treatment: smoking cessation, LTOT (only survival benefit), pharmacological step-up table (SABA/SAMA to triple therapy)
  • AECOPD management: controlled O2, nebulizers, steroids, antibiotics, NIV
  • Dental relevance: caution with sedation/GA, erythromycin-theophylline interaction
TOPIC 2 - COR PULMONALE
  • Definition (RV hypertrophy/failure from lung disease, NOT left heart)
  • Etiology table: lung parenchymal (COPD = MC), vascular (PE = acute), chest wall, altitude
  • Pathophysiology: hypoxia -> HPV -> PAH -> RV hypertrophy -> RV failure
  • Clinical features: signs table (raised JVP, parasternal heave, loud P2, TR murmur, hepatomegaly, edema)
  • Investigations: ECG (P pulmonale, RV hypertrophy), Echo (most useful), ABG, polycythemia, right heart catheterization (gold standard)
  • Treatment table: LTOT (primary + only proven survival benefit), diuretics, anticoagulation, pulmonary vasodilators (sildenafil, bosentan), phlebotomy
  • Prognosis: 50% reduction in 5-year survival if PAP >25 mmHg
TOPIC 3 - TUBERCULOSIS
  • Organism (M. tuberculosis - AFB, ZN stain), epidemiology (India = highest burden)
  • Pathogenesis: primary TB (Ghon complex, Ranke complex) vs post-primary reactivation
  • Classification table: pulmonary, miliary, extrapulmonary, LTBI, MDR/XDR
  • Clinical: constitutional (fever/night sweats/weight loss) + respiratory (cough >3 weeks, hemoptysis)
  • Investigations table: AFB smear (ZN stain), culture (gold standard), CXR (upper lobe cavitation), Mantoux, IGRA, GeneXpert (most rapid - 2 hours), ADA for pleural TB
  • Treatment regimen: 2HRZE + 4HR for new cases; drug side effects table (INH neuropathy, rifampicin orange urine, ethambutol optic neuritis)
  • Dental: active TB = contraindication to elective treatment; N95 mask; rifampicin enzyme inducer; oral TB ulcer
TOPIC 4 - PLEURAL DISEASE
  • Pleural effusion definition + Light's criteria (3 criteria table)
  • Transudate vs exudate causes table (CCF = MC transudate; pneumonia = MC exudate; TB = MC in developing countries)
  • Clinical features + classical signs table (stony dullness = most characteristic)
  • Investigations: CXR (blunted costophrenic angle), USG, CT, thoracocentesis + fluid analysis (protein, LDH, cytology, ADA, culture)
  • Treatment: drain + treat cause; pleurodesis for malignant effusions; VATS
  • Empyema: definition + 3 stages (exudative, fibrinopurulent, organizing), causes, diagnosis (pH <7.2, glucose low, frank pus), treatment (ICD + antibiotics + fibrinolytics + decortication)
TOPIC 5 - PNEUMOTHORAX
  • Definition (air in pleural space, lung collapse)
  • Types table: PSP (young males, blebs), SSP (COPD, TB etc.), traumatic/iatrogenic, tension (life-threatening)
  • Clinical features + signs table (hyperresonance = key sign; tension = trachea deviated AWAY)
  • Tension pneumothorax signs (emergency - no delay for X-ray)
  • Investigations: CXR (investigation of choice), CT (most accurate), USG (absent lung sliding)
  • Management table: small PSP = O2 + observe; large PSP = aspiration; SSP = ICD; tension = IMMEDIATE needle decompression (14G, 2nd ICS MCL)
  • Complications: re-expansion pulmonary edema, haemopneumothorax, recurrence (50%)
  • Dental: N2O contraindicated in pneumothorax (expands cavity); positive pressure ventilation risk in COPD

Write me a shrot notes for the following topics from anil k tripathi book of general medicine for bds gujarat university for 3 year exams about 7-8 marks Male concise to the point precise ans to the topics are Nephrotic syndrome Acute and rapidly progressive glomerulonephritides Acute kidney injury Chronic kidney disease Kidney failure Indications of liver and kidney transplant In pdf form

Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Finding Sources
Writing File

~/bds-notes/generate_notes3.py

from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY

doc = SimpleDocTemplate(
    "/tmp/workspace/bds-notes/General_Medicine_Short_Notes_BDS_Part3.pdf",
    pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2*cm, bottomMargin=2*cm
)

styles = getSampleStyleSheet()

title_style = ParagraphStyle('T', fontSize=18, textColor=colors.HexColor('#4a148c'),
    spaceAfter=4, alignment=TA_CENTER, fontName='Helvetica-Bold')
subtitle_style = ParagraphStyle('S', fontSize=10, textColor=colors.HexColor('#4a4a4a'),
    spaceAfter=10, alignment=TA_CENTER, fontName='Helvetica-Oblique')
body_style = ParagraphStyle('B', fontSize=9.5, textColor=colors.HexColor('#212121'),
    spaceAfter=3, spaceBefore=1, leading=14, alignment=TA_JUSTIFY, fontName='Helvetica')
bullet_style = ParagraphStyle('BL', fontSize=9.5, textColor=colors.HexColor('#212121'),
    spaceAfter=2, spaceBefore=1, leading=13, leftIndent=14, fontName='Helvetica')
bold_label = ParagraphStyle('BLD', fontSize=9.5, textColor=colors.HexColor('#4a148c'),
    spaceAfter=1, spaceBefore=3, fontName='Helvetica-Bold')
footer_style = ParagraphStyle('F', fontSize=8, textColor=colors.HexColor('#757575'), alignment=TA_CENTER)

def topic_banner(title, number):
    data = [[Paragraph('<font color="white"><b>TOPIC %s: %s</b></font>' % (number, title),
        ParagraphStyle('bn', fontSize=12, textColor=colors.white, fontName='Helvetica-Bold', alignment=TA_CENTER))]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#4a148c')),
        ('TOPPADDING', (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
    ]))
    return t

def section_box(title):
    data = [[Paragraph('<b>%s</b>' % title, ParagraphStyle('sb', fontSize=10,
        textColor=colors.HexColor('#4a148c'), fontName='Helvetica-Bold'))]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#f3e5f5')),
        ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 8),
        ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor('#7b1fa2')),
    ]))
    return t

def mk_table(data_list, col_widths):
    t = Table(data_list, colWidths=col_widths)
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#f3e5f5')),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#ce93d8')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#fce4ec')]),
    ]))
    return t

def bp(t): return '<b>%s</b>' % t
def it(t): return '<i>%s</i>' % t
def b(lbl): return Paragraph(bp(lbl), bold_label)
def p(txt): return Paragraph(txt, body_style)
def bl(txt): return Paragraph('- %s' % txt, bullet_style)
def sp(h=0.1): return Spacer(1, h*cm)

story = []

# HEADER
story += [sp(0.3),
    Paragraph("GENERAL MEDICINE", title_style),
    Paragraph("Short Notes for BDS 3rd Year | Gujarat University Examinations", subtitle_style),
    Paragraph("Based on Anil K. Tripathi - General Medicine for BDS", ParagraphStyle(
        'ref', fontSize=9, textColor=colors.HexColor('#757575'), alignment=TA_CENTER,
        fontName='Helvetica-Oblique', spaceAfter=4)),
    Paragraph("Each topic: 7-8 Marks | Concise, Precise, Exam-Oriented", ParagraphStyle(
        'info', fontSize=9, textColor=colors.HexColor('#c62828'), alignment=TA_CENTER,
        fontName='Helvetica-Bold', spaceAfter=10)),
    HRFlowable(width="100%", thickness=2, color=colors.HexColor('#4a148c')),
    sp(0.3)]

toc = mk_table([
    [Paragraph(bp("No."), body_style), Paragraph(bp("Topic"), body_style), Paragraph(bp("Marks"), body_style)],
    [p("1."), p("Nephrotic Syndrome"), p("7-8")],
    [p("2."), p("Acute and Rapidly Progressive Glomerulonephritis"), p("7-8")],
    [p("3."), p("Acute Kidney Injury (AKI)"), p("7-8")],
    [p("4."), p("Chronic Kidney Disease (CKD)"), p("7-8")],
    [p("5."), p("Kidney Failure (End-Stage Renal Disease)"), p("7-8")],
    [p("6."), p("Indications for Liver and Kidney Transplant"), p("7-8")],
], [1.5*cm, 13*cm, 2.5*cm])
story += [toc, sp(0.5), PageBreak()]

# ============================================================
# TOPIC 1: NEPHROTIC SYNDROME
# ============================================================
story += [topic_banner("NEPHROTIC SYNDROME", "1"), sp(0.2)]

story += [section_box("Definition")]
story += [p("Nephrotic syndrome is a clinical syndrome characterized by the tetrad of: "
    + bp("(1) Heavy proteinuria (>3.5 g/day in adults; >40 mg/m2/hr in children)") + ", "
    + bp("(2) Hypoalbuminemia (<30 g/L)") + ", "
    + bp("(3) Generalized edema (anasarca)") + ", and "
    + bp("(4) Hyperlipidemia + lipiduria") + ". "
    "It results from increased glomerular permeability to proteins."), sp()]

story += [section_box("Etiology / Causes")]
story += [mk_table([
    [Paragraph(bp("Primary (Idiopathic) GN"), body_style), Paragraph(bp("Secondary Causes"), body_style)],
    [Paragraph("- " + bp("Minimal Change Disease (MCD)") + " - MC in children (80%)\n"
        "- " + bp("Focal Segmental Glomerulosclerosis (FSGS)") + " - MC in adults\n"
        "- Membranous Nephropathy - MC in middle-aged adults\n"
        "- Membranoproliferative GN (MPGN)\n"
        "- Mesangial proliferative GN", body_style),
     Paragraph("- " + bp("Diabetes mellitus") + " (Diabetic nephropathy - MC secondary cause)\n"
        "- " + bp("Systemic Lupus Erythematosus") + " (Lupus nephritis)\n"
        "- Amyloidosis\n"
        "- Infections: Hepatitis B, C; HIV; Malaria (P. malariae - quartan)\n"
        "- Drugs: Gold, penicillamine, NSAIDs, heroin\n"
        "- Malignancy: Hodgkin lymphoma (MCD), solid tumors (memb. nephropathy)", body_style)],
], [8.5*cm, 8.5*cm]), sp()]

story += [section_box("Pathophysiology")]
story += [p(bp("Loss of glomerular charge barrier") + " (loss of polyanion - heparan sulfate) + structural defect "
    "in glomerular filtration membrane (podocyte injury) leads to massive proteinuria. "
    "Hypoalbuminemia reduces plasma oncotic pressure, causing fluid shift to interstitium (edema). "
    "Liver compensates with increased lipoprotein synthesis causing hyperlipidemia. "
    "Lipiduria occurs when lipoprotein particles cross damaged GBM."), sp()]

story += [section_box("Clinical Features")]
story += [b("Symptoms:")]
for x in ["Puffiness of face - early morning periorbital edema (characteristic first symptom)",
    bp("Pitting edema") + " - bilateral, dependent; progresses to anasarca (generalized edema)",
    bp("Ascites") + " - abdominal distension; pleural effusions (dyspnoea)",
    "Frothy urine (heavy proteinuria - foam persists)",
    "Reduced urine output",
    "Symptoms of underlying cause (e.g. rash in SLE, hyperglycemia in DM)"]:
    story.append(bl(x))

story += [b("Complications:")]
comp_data = mk_table([
    [Paragraph(bp("Complication"), body_style), Paragraph(bp("Mechanism / Notes"), body_style)],
    [p("Infections"), p("Hypogammaglobulinemia (IgG loss in urine); impaired opsonization. "
        "Spontaneous bacterial peritonitis, cellulitis, pneumococcal sepsis (children).")],
    [p("Thromboembolism"), p("Loss of antithrombin III, protein C, S; increased clotting factors. "
        "Deep vein thrombosis, renal vein thrombosis (flank pain, hematuria), pulmonary embolism.")],
    [p("Hyperlipidemia / Atherosclerosis"), p("Increased LDL, VLDL synthesis; decreased HDL. Accelerated atherosclerosis.")],
    [p("Acute Kidney Injury"), p("Reduced renal perfusion (underfill), nephrotoxic drugs, renal vein thrombosis.")],
    [p("Hypothyroidism"), p("Loss of thyroxine-binding globulin in urine (low total T4; free T4 often normal).")],
    [p("Vitamin D deficiency / Osteoporosis"), p("Loss of Vitamin D binding protein and 25-OH Vit D in urine.")],
], [4*cm, 13*cm])
story += [comp_data, sp()]

story += [section_box("Investigations")]
for x in [
    bp("Urine Routine") + " - " + bp("3+ or 4+ proteinuria") + " on dipstick; fatty casts, oval fat bodies, maltese crosses on polarized light; lipiduria",
    bp("24-hour urine protein") + " > 3.5 g/day (or spot urine protein:creatinine ratio >3500 mg/g)",
    bp("Serum albumin") + " < 30 g/L (often < 20 g/L in severe cases)",
    bp("Serum lipids") + " - elevated total cholesterol, LDL, VLDL; triglycerides raised",
    bp("Serum creatinine / BUN") + " - assess renal function",
    bp("Renal biopsy") + " - " + bp("definitive diagnosis") + "; indicated in adults, secondary NS, steroid-resistant NS. Electron microscopy key for MCD (foot process effacement)",
    bp("ANA, anti-dsDNA") + " - SLE; Hep B/C serology; HIV; serum complement (C3/C4)",
    bp("Chest X-ray") + " - pleural effusions; CXR/Echo for cardiomegaly",
]:
    story.append(bl(x))

story += [section_box("Treatment")]
story += [b("General Measures:")]
for x in ["Low-sodium diet (< 2 g/day) - reduces edema",
    "Moderate protein diet (0.8-1.0 g/kg/day) - high protein increases proteinuria",
    bp("Diuretics") + ": Furosemide (loop) + Spironolactone (aldosterone antagonist) for edema",
    bp("ACE inhibitors / ARBs") + " (Ramipril / Losartan) - reduce proteinuria and slow progression",
    "Statins - treat hyperlipidemia",
    bp("Anticoagulation") + " - if renal vein thrombosis or serum albumin <20 g/L (high thrombosis risk)",
    "Vaccinations: Pneumococcal, Influenza (infection risk)"]:
    story.append(bl(x))

story += [b("Specific Treatment by Cause:")]
rx_data = mk_table([
    [Paragraph(bp("Cause"), body_style), Paragraph(bp("Specific Treatment"), body_style)],
    [p("Minimal Change Disease (MCD)"), p(bp("Oral prednisolone 1 mg/kg/day") + " x 4-8 weeks; 90% respond. "
        "Relapse common - cyclophosphamide or cyclosporine for steroid-dependent/resistant cases.")],
    [p("FSGS"), p("Prednisolone - slower response than MCD. Cyclosporine/tacrolimus for steroid-resistant.")],
    [p("Membranous Nephropathy"), p("ACE inhibitor first. Immunosuppression (cyclophosphamide + prednisolone) "
        "for high-risk patients (Ponticelli regimen).")],
    [p("Diabetic Nephropathy"), p("Strict glycemic control, RAAS blockade (ACE-I/ARB), SGLT2 inhibitors (fludgliflozin).")],
    [p("Lupus Nephritis"), p("Hydroxychloroquine + Mycophenolate mofetil + steroids.")],
], [5*cm, 12*cm])
story += [rx_data, sp()]

story += [b("Dental Relevance:")]
story += [p("(1) Patients on " + bp("corticosteroids") + " need steroid cover before dental procedures (adrenal suppression risk). "
    "(2) Increased " + bp("infection risk") + " (immunosuppressed) - prophylactic antibiotics if needed. "
    "(3) " + bp("NSAIDs are contraindicated") + " - worsen renal function and proteinuria. Use paracetamol. "
    "(4) Cyclosporine causes " + bp("gingival hyperplasia") + " - important oral side effect; needs regular dental review. "
    "(5) Edematous patients - check BP before procedures.")]

story.append(PageBreak())

# ============================================================
# TOPIC 2: ACUTE AND RAPIDLY PROGRESSIVE GLOMERULONEPHRITIS
# ============================================================
story += [topic_banner("ACUTE AND RAPIDLY PROGRESSIVE GLOMERULONEPHRITIS", "2"), sp(0.2)]

story += [section_box("Definitions")]
story += [mk_table([
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Definition"), body_style)],
    [p("Acute Nephritic Syndrome (ANS)"), p("Sudden onset of hematuria (smoky/cola-coloured urine), oliguria, "
        "hypertension, proteinuria (<3.5 g/day), and edema with declining GFR. "
        "Hallmark: " + bp("red cell casts in urine") + " (pathognomonic of glomerular bleeding).")],
    [p("Rapidly Progressive GN (RPGN)"), p("Clinical syndrome with rapid deterioration in renal function (loss of 50% GFR "
        "within weeks to months), with nephritic features. Histology shows " + bp("crescents in >50% of glomeruli") +
        " (crescent = proliferating parietal epithelial cells + macrophages filling Bowman's capsule).")],
], [4.5*cm, 12.5*cm]), sp()]

story += [section_box("Acute Nephritic Syndrome - Etiology")]
story += [mk_table([
    [Paragraph(bp("Category"), body_style), Paragraph(bp("Causes"), body_style)],
    [p("Post-Infectious (MC overall)"), p(bp("Post-streptococcal GN (PSGN)") + " - " + bp("MC cause in children") +
        "; follows Group A beta-hemolytic Streptococcal (GABHS) pharyngitis (1-3 weeks) or skin infection (3-6 weeks). "
        "Immune complex deposition. C3 low, C4 normal. ASO titre elevated.")],
    [p("IgA Nephropathy\n(Berger's disease)"), p(bp("MC primary GN worldwide") + ". Hematuria within 24-48 hours of URTI "
        "(synpharyngitic hematuria - unlike PSGN which is latent). IgA deposits in mesangium. Normal complement.")],
    [p("Other Infections"), p("Infective endocarditis, visceral abscess, hepatitis B/C, HIV, malaria")],
    [p("Systemic"), p("SLE (lupus nephritis - anti-dsDNA, low C3 C4), HSP (Henoch-Schonlein Purpura), "
        "polyarteritis nodosa, Wegener's granulomatosis (ANCA positive)")],
    [p("Hereditary"), p("Alport syndrome (X-linked; thin basement membrane disease; deafness + eye anomalies + hematuria)")],
], [4.5*cm, 12.5*cm]), sp()]

story += [section_box("Post-Streptococcal GN - Key Features")]
for x in [
    bp("Latent period") + ": 1-3 weeks after throat infection; 3-6 weeks after skin (impetigo)",
    bp("Age") + ": children 5-15 years; boys > girls",
    bp("Classic presentation") + ": Cola-coloured urine (hematuria), periorbital puffiness, hypertension, oliguria",
    bp("Lab") + ": Red cell casts (pathognomonic); low C3 (returns to normal by 6-8 weeks); normal C4; raised ASO titre; proteinuria (<2 g/day)",
    bp("Biopsy") + ": Diffuse proliferative GN; subepithelial 'humps' on EM (immune complex deposits)",
    bp("Prognosis") + ": Excellent in children (>95% recover fully); adults have worse prognosis",
    bp("Treatment") + ": Supportive - salt/fluid restriction, antihypertensives, diuretics; penicillin to eradicate streptococcus",
]:
    story.append(bl(x))

story += [sp(), section_box("Rapidly Progressive GN (RPGN) - Classification")]
rpgn_data = mk_table([
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Immunology"), body_style), Paragraph(bp("Examples"), body_style)],
    [p("Type I\n(Anti-GBM)"), p("Linear IgG along GBM on IF"), p(bp("Goodpasture syndrome") + " - anti-GBM antibody causes pulmonary hemorrhage + nephritis. "
        "Young males (pulmonary) or older females (renal only). EMERGENCY.")],
    [p("Type II\n(Immune complex)"), p("Granular immune deposits on IF (lumpy bumpy)"), p("Post-streptococcal GN, lupus nephritis, IgA nephropathy, MPGN, "
        "cryoglobulinemia, endocarditis-related GN")],
    [p("Type III\n(Pauci-immune / ANCA)"), p("No / minimal Ig deposits on IF; ANCA positive"), p(bp("Microscopic polyangiitis") + " (p-ANCA / anti-MPO), "
        bp("Granulomatosis with polyangiitis") + " (GPA/Wegener's - c-ANCA / anti-PR3), "
        "Eosinophilic GPA (Churg-Strauss)")],
], [3*cm, 5*cm, 9*cm])
story += [rpgn_data, sp()]

story += [section_box("RPGN - Clinical Features and Treatment")]
story += [p(bp("Clinical") + ": Rapid decline in GFR over days-weeks; hematuria, proteinuria, hypertension, oliguria/anuria; "
    "systemic features (fever, arthralgia, rash) depending on cause. "
    "Goodpasture: hemoptysis + renal failure. Wegener's/MPA: saddle-nose deformity, sinusitis, pulmonary infiltrates.")]
story += [b("Investigations:")]
for x in [
    bp("Urinalysis") + ": Red cell casts, proteinuria",
    bp("Serology") + ": ANCA (c-ANCA/p-ANCA), anti-GBM antibody, ANA, complement (C3/C4), ASO, cryoglobulins, hepatitis serology",
    bp("Renal biopsy (urgent)") + ": crescents in >50% glomeruli; IF pattern (linear vs granular vs pauci-immune)",
    bp("CXR") + ": pulmonary hemorrhage (Goodpasture, Wegener's)",
]:
    story.append(bl(x))

story += [b("Treatment (URGENT - Renal function declines rapidly):")]
for x in [
    bp("Pulsed IV methylprednisolone") + " (1g/day x 3 days) then oral prednisolone 1 mg/kg/day",
    bp("Cyclophosphamide") + " (oral or IV) - immunosuppression; used with steroids for ANCA-RPGN",
    bp("Plasma exchange (Plasmapheresis)") + " - first line in Goodpasture syndrome (removes anti-GBM antibodies); "
    "also ANCA-RPGN with pulmonary hemorrhage",
    bp("Rituximab") + " - alternative to cyclophosphamide for ANCA vasculitis (non-inferior, less toxic)",
    "Dialysis support if severe AKI develops",
    bp("Monitor closely") + ": renal biopsy guides prognosis; crescents <50% = better prognosis",
]:
    story.append(bl(x))

story += [b("Dental Relevance:")]
story += [p("(1) " + bp("Streptococcal throat infections") + " can trigger post-streptococcal GN - aggressive treatment with penicillin for GABHS throat infection important. "
    "(2) Patients with RPGN on immunosuppressants (cyclophosphamide) have severe " + bp("myelosuppression and infection risk") + " - check CBC before any dental procedure. "
    "(3) Avoid NSAIDs in all glomerulonephritis patients. "
    "(4) Dental infections can trigger exacerbations of IgA nephropathy.")]

story.append(PageBreak())

# ============================================================
# TOPIC 3: ACUTE KIDNEY INJURY
# ============================================================
story += [topic_banner("ACUTE KIDNEY INJURY (AKI)", "3"), sp(0.2)]

story += [section_box("Definition - KDIGO Criteria (Any ONE of the following)")]
story += [mk_table([
    [Paragraph(bp("Criterion"), body_style), Paragraph(bp("Threshold"), body_style)],
    [p("Rise in serum creatinine"), p(">=0.3 mg/dL (26.5 micromol/L) within 48 hours OR >=1.5x baseline within 7 days")],
    [p("Reduced urine output"), p("< 0.5 mL/kg/hr for >= 6 hours")],
], [6*cm, 11*cm]), sp()]

story += [section_box("KDIGO Staging of AKI")]
story += [mk_table([
    [Paragraph(bp("Stage"), body_style), Paragraph(bp("Serum Creatinine"), body_style), Paragraph(bp("Urine Output"), body_style)],
    [p("Stage 1"), p("1.5-1.9x baseline OR rise of >=0.3 mg/dL"), p("<0.5 mL/kg/hr for 6-12 hours")],
    [p("Stage 2"), p("2.0-2.9x baseline"), p("<0.5 mL/kg/hr for >=12 hours")],
    [p("Stage 3"), p(">=3x baseline OR >=4.0 mg/dL OR initiation of KRT"), p("<0.3 mL/kg/hr for >=24h OR anuria >=12h")],
], [2.5*cm, 8.5*cm, 6*cm]), sp()]

story += [section_box("Etiology / Classification")]
story += [mk_table([
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Mechanism"), body_style), Paragraph(bp("Causes"), body_style)],
    [p(bp("Pre-renal AKI") + "\n(~55-60%)"), p("Reduced renal perfusion (low blood flow to kidneys); GFR drops due to hypovolemia or low cardiac output; tubules intact"), p(
        "- Volume depletion: vomiting, diarrhea, burns, hemorrhage\n"
        "- Hypotension: septic shock, cardiogenic shock\n"
        "- Cardiac failure, liver failure, nephrotic syndrome\n"
        "- NSAIDs, ACE-I/ARBs (reduce efferent arteriolar tone)\n"
        "- Renal artery stenosis (bilateral)")],
    [p(bp("Intrinsic Renal AKI") + "\n(~40%)"), p("Direct damage to renal parenchyma (tubules, glomeruli, interstitium, vessels)"), p(
        "- " + bp("Acute Tubular Necrosis (ATN)") + " - MC cause of intrinsic AKI\n"
        "  Ischemic ATN (prolonged pre-renal state)\n"
        "  Nephrotoxic ATN: aminoglycosides, contrast dye (CIAKI), cisplatin, myoglobinuria, hemoglobinuria\n"
        "- " + bp("Acute Interstitial Nephritis (AIN)") + ": drugs (NSAIDs, penicillins, PPIs), infections\n"
        "- Glomerulonephritis (RPGN)\n"
        "- Renal vessel disease: renal artery thrombosis, HUS/TTP")],
    [p(bp("Post-renal AKI") + "\n(~5%)"), p("Obstruction to urine outflow; increases back pressure; tubular function initially preserved"), p(
        "- " + bp("BPH (MC in elderly males)") + " - bilateral ureteral obstruction\n"
        "- Renal stones (bilateral, or solitary kidney)\n"
        "- Pelvic malignancy (cervix, bladder, prostate, colon)\n"
        "- Urethral stricture\n"
        "- Retroperitoneal fibrosis")],
], [3.5*cm, 4.5*cm, 9*cm]), sp()]

story += [section_box("Pre-renal vs Intrinsic (ATN) - Key Differentiation")]
story += [mk_table([
    [Paragraph(bp("Parameter"), body_style), Paragraph(bp("Pre-renal"), body_style), Paragraph(bp("ATN (Intrinsic)"), body_style)],
    [p("Urine Na"), p("< 20 mEq/L (kidneys conserve Na)"), p("> 40 mEq/L (tubules damaged, cannot conserve)")],
    [p("FENa (Fractional excretion of Na)"), p("< 1%"), p("> 2%")],
    [p("Urine osmolality"), p("> 500 mOsm/kg"), p("< 350 mOsm/kg (isosthenuria)")],
    [p("Urine specific gravity"), p("> 1.020"), p("~1.010 (fixed)")],
    [p("Urine sediment"), p("Bland / hyaline casts"), p(bp("Muddy brown (granular) casts") + " (ATN)")],
    [p("Response to fluids"), p("GFR improves rapidly"), p("No improvement with fluids")],
    [p("BUN:Creatinine ratio"), p("> 20:1 (increased urea reabsorption)"), p("10-15:1")],
], [5*cm, 6*cm, 6*cm]), sp()]

story += [section_box("Clinical Features")]
story += [b("Oliguric Phase (0-2 weeks):")]
for x in [
    bp("Oliguria") + " (<400 mL/day) or anuria (<100 mL/day)",
    bp("Fluid overload") + ": edema, pulmonary edema, hypertension",
    bp("Uremia") + ": nausea, vomiting, lethargy, confusion, hiccups, pericarditis",
    bp("Hyperkalemia") + ": peaked T waves on ECG, arrhythmias, cardiac arrest",
    bp("Metabolic acidosis") + ": Kussmaul breathing",
    "Anemia (normochromic, normocytic)",
]:
    story.append(bl(x))

story += [b("Diuretic / Polyuric Phase (2-3 weeks):")]
for x in [
    "Urine output >1-2 L/day (tubular function recovering but concentration ability impaired)",
    "Risk of " + bp("hypokalemia, hyponatremia, dehydration"),
    "Gradual improvement in creatinine",
]:
    story.append(bl(x))

story += [b("Recovery Phase (up to 12 months):")]
for x in [
    "GFR returns toward normal; some patients develop permanent CKD",
    "Complete recovery in most ischemic ATN; nephrotoxic ATN has better prognosis",
]:
    story.append(bl(x))

story += [section_box("Investigations")]
for x in [
    bp("Serum creatinine and BUN") + " - rise (creatinine rises ~1-2 mg/dL/day in oliguric ATN)",
    bp("Serum electrolytes") + " - hyperkalemia, hyponatremia, hypocalcemia, hyperphosphatemia",
    bp("ABG") + " - metabolic acidosis (raised anion gap)",
    bp("Urine analysis + microscopy") + " - see FENa table; casts; specific gravity",
    bp("Renal ultrasound") + " - " + bp("first imaging") + "; rules out obstruction; assess kidney size (small in CKD, normal/large in AKI)",
    bp("ECG") + " - hyperkalemia changes (peaked T, widened QRS, sine wave pattern)",
    bp("CBC") + " - anemia; raised WBC if sepsis",
    bp("Blood culture") + " - if sepsis-related AKI",
]:
    story.append(bl(x))

story += [section_box("Management")]
story += [b("General Principles:")]
for x in [
    bp("Identify and treat the cause") + ": correct hypovolemia (IV fluids), relieve obstruction, stop nephrotoxic drugs",
    bp("Fluid balance") + ": fluid challenge if pre-renal; restrict if oliguric overloaded (ins/outs chart)",
    bp("Treat hyperkalemia") + " - URGENT: calcium gluconate (stabilize membrane), insulin+dextrose (shift K in), salbutamol nebulization, sodium bicarbonate, kayexalate (resin), dialysis",
    bp("Treat metabolic acidosis") + ": sodium bicarbonate if pH <7.2",
    "Nutritional support: adequate calories; avoid excess protein",
    "Careful drug dosing - adjust for eGFR; avoid nephrotoxins",
]:
    story.append(bl(x))

story += [b("Renal Replacement Therapy (RRT) - Indications (AEIOU):")]
story += [mk_table([
    [Paragraph(bp("Mnemonic"), body_style), Paragraph(bp("Indication"), body_style), Paragraph(bp("Details"), body_style)],
    [p("A"), p("Acidosis"), p("Metabolic acidosis pH <7.1 not responding to bicarbonate")],
    [p("E"), p("Electrolytes"), p("Refractory hyperkalemia (K+ >6.5 mEq/L with ECG changes or not responding to treatment)")],
    [p("I"), p("Ingestion"), p("Drug/toxin overdose (e.g. methanol, ethylene glycol, salicylates, lithium)")],
    [p("O"), p("Overload"), p("Fluid overload with pulmonary edema not responding to diuretics")],
    [p("U"), p("Uremia"), p("Uremic pericarditis, encephalopathy, bleeding, serum urea >30 mmol/L with symptoms")],
], [1*cm, 3*cm, 13*cm]), sp()]

story += [p(bp("Modalities") + ": Intermittent hemodialysis (IHD) - stable patients; "
    "Continuous RRT (CRRT - CVVHDF) - hemodynamically unstable ICU patients; "
    "Peritoneal dialysis (PD) - where HD/CRRT unavailable.")]

story += [b("Dental Relevance:")]
story += [p("(1) " + bp("NSAIDs and COX-2 inhibitors are contraindicated") + " in AKI risk patients (reduce renal prostaglandins, cause vasoconstriction). "
    "(2) " + bp("Contrast dye (iodinated)") + " for dental radiographic procedures not relevant, but IV contrast for CT scans in patients with renal impairment needs N-acetylcysteine pre-treatment and hydration. "
    "(3) Dental infections causing " + bp("sepsis") + " are a precipitating cause of AKI. "
    "(4) Antibiotics: avoid aminoglycosides (gentamicin) in renal impairment. Metronidazole and amoxicillin are safe; adjust penicillin doses.")]

story.append(PageBreak())

# ============================================================
# TOPIC 4: CHRONIC KIDNEY DISEASE
# ============================================================
story += [topic_banner("CHRONIC KIDNEY DISEASE (CKD)", "4"), sp(0.2)]

story += [section_box("Definition (KDIGO 2012)")]
story += [p("CKD is defined as " + bp("abnormalities of kidney structure or function, present for >3 months, with implications for health") + ". "
    "Requires ANY ONE of: "
    bp("GFR <60 mL/min/1.73m2") + " for >3 months; OR "
    bp("markers of kidney damage") + " (albuminuria, hematuria, abnormal imaging/biopsy) for >3 months.")]

story += [section_box("GFR-based Staging (KDIGO)")]
story += [mk_table([
    [Paragraph(bp("Stage (G)"), body_style), Paragraph(bp("GFR (mL/min/1.73m2)"), body_style), Paragraph(bp("Description"), body_style)],
    [p("G1"), p(">= 90"), p("Normal/High GFR + markers of kidney damage")],
    [p("G2"), p("60-89"), p("Mildly decreased (with markers of damage)")],
    [p("G3a"), p("45-59"), p("Mildly-moderately decreased")],
    [p("G3b"), p("30-44"), p("Moderately-severely decreased")],
    [p("G4"), p("15-29"), p("Severely decreased - prepare for RRT")],
    [p("G5 (ESKD)"), p("< 15"), p("Kidney failure - RRT or transplant required")],
], [2.5*cm, 5.5*cm, 9*cm]), sp()]

story += [section_box("Common Causes of CKD")]
story += [mk_table([
    [Paragraph(bp("Cause"), body_style), Paragraph(bp("Details"), body_style)],
    [p(bp("Diabetic Nephropathy") + " (MC cause worldwide)"),
     p("Occurs in ~40% of type 1 and type 2 DM; Kimmelstiel-Wilson nodules (nodular glomerulosclerosis) on biopsy; proteinuria precedes GFR decline")],
    [p(bp("Hypertensive Nephrosclerosis") + " (2nd MC)"),
     p("Benign nephrosclerosis (afferent arteriolar hyalinosis) vs malignant (fibrinoid necrosis)")],
    [p("Chronic GN"),
     p("FSGS, IgA nephropathy, MPGN, lupus nephritis, RPGN")],
    [p("Polycystic Kidney Disease (ADPKD)"),
     p("Autosomal dominant; PKD1 (chr 16) or PKD2 (chr 4); MC genetic cause; bilateral cysts; flank pain, hypertension, hematuria")],
    [p("Chronic Pyelonephritis / Reflux Nephropathy"),
     p("Recurrent UTI with reflux causing progressive scarring")],
    [p("Obstructive Uropathy"), p("BPH, stones, malignancy - chronic back pressure injury")],
    [p("Others"), p("Amyloidosis, SLE, sickle cell disease, analgesic nephropathy, contrast nephropathy")],
], [5*cm, 12*cm]), sp()]

story += [section_box("Pathophysiology - Progression of CKD")]
story += [p("Regardless of initial cause, CKD progresses via: "
    "(1) " + bp("Hyperfiltration") + " - remaining nephrons hyperfiltrate (adaptive but ultimately injurious). "
    "(2) " + bp("Intraglomerular hypertension") + " - activates TGF-beta, causing glomerulosclerosis. "
    "(3) " + bp("Proteinuria") + " - tubular proteinuria causes tubular injury and interstitial fibrosis. "
    "(4) Progressive loss of nephrons - irreversible scarring.")]

story += [section_box("Clinical Features - Uremic Syndrome")]
story += [mk_table([
    [Paragraph(bp("System"), body_style), Paragraph(bp("Features"), body_style)],
    [p("General"), p("Fatigue, weakness, weight loss, pruritis (itch), 'uremic frost' (urea crystal deposits on skin in severe uremia)")],
    [p("CVS"), p(bp("Hypertension") + " (renin excess, fluid overload); accelerated atherosclerosis; "
        "Uremic pericarditis (friction rub); LVH; cardiac failure")],
    [p("Hematological"), p(bp("Normochromic normocytic anemia") + " (reduced EPO production); "
        "bleeding tendency (platelet dysfunction); thrombocytopenia")],
    [p("Neurological"), p("Uremic encephalopathy: confusion, seizures, coma; Peripheral neuropathy (restless legs, burning feet, glove-stocking pattern); asterixis (flapping tremor)")],
    [p("GI"), p("Nausea, vomiting, anorexia, hiccups, peptic ulceration, uremic fetor (ammonia breath), GI bleeding")],
    [p("Bones (Renal Osteodystrophy)"), p(bp("Secondary hyperparathyroidism") + ": low Vit D (kidneys fail to convert 25-OH-D3 to active 1,25-OH-D3) + hyperphosphatemia + hypocalcemia -> PTH rises -> bone resorption. "
        "Osteitis fibrosa cystica, osteomalacia, adynamic bone disease, vascular calcification")],
    [p("Metabolic"), p("Metabolic acidosis, hyperkalemia, hyponatremia, hyperphosphatemia, hypocalcemia, hyperuricemia (gout)")],
    [p("Endocrine"), p("Impaired glucose tolerance, hypothyroidism, hypogonadism, infertility, impotence, amenorrhoea")],
    [p("Respiratory"), p("Kussmaul breathing (acidosis), pulmonary edema, pleuritis")],
], [4*cm, 13*cm]), sp()]

story += [section_box("Investigations")]
for x in [
    bp("Serum creatinine, BUN, eGFR (CKD-EPI)") + " - assess degree of kidney function",
    bp("Urinalysis + 24-hr urine protein") + " - proteinuria, hematuria, casts; albuminuria staging (A1/A2/A3)",
    bp("Serum electrolytes") + " - hyperkalemia, hyperphosphatemia, hypocalcemia",
    bp("CBC") + " - normochromic normocytic anemia (reduced EPO)",
    bp("Serum PTH") + " - elevated secondary hyperparathyroidism",
    bp("Renal ultrasound") + " - small, echogenic kidneys bilaterally (CKD); large kidneys in DM, ADPKD, amyloid",
    bp("Renal biopsy") + " - if cause unclear; avoid if small kidneys (advanced scarring)",
    bp("Lipid profile") + " - dyslipidemia common; increased CVS risk",
]:
    story.append(bl(x))

story += [section_box("Management")]
story += [b("Slow CKD Progression:")]
for x in [
    bp("BP control") + " - target <130/80 mmHg; " + bp("ACE inhibitors / ARBs") + " first line (reduce proteinuria and intraglomerular pressure)",
    bp("Glycemic control") + " - HbA1c <7% in diabetic CKD; SGLT2 inhibitors (empagliflozin) have proven renoprotective benefit",
    "Treat underlying cause (immunosuppression for GN)",
    bp("Avoid nephrotoxins") + ": NSAIDs, contrast dye, aminoglycosides, herbal remedies",
    "Low-protein diet: 0.6-0.8 g/kg/day (reduces hyperfiltration and uremic toxin load)",
    "Smoking cessation, weight reduction",
]:
    story.append(bl(x))

story += [b("Manage Complications:")]
for x in [
    bp("Anemia") + ": Erythropoiesis-stimulating agents (ESA) - Erythropoietin/darbepoetin + IV iron (when eGFR <30 or Hb <10 g/dL)",
    bp("Renal Osteodystrophy") + ": Active Vit D (calcitriol/alfacalcidol), phosphate binders (calcium carbonate, sevelamer), cinacalcet (calcimimetic for hyperparathyroidism)",
    bp("Hyperkalemia") + ": low K+ diet, avoid RAAS drugs if severe K+, patiromer/sodium zirconium cyclosilicate",
    bp("Metabolic acidosis") + ": oral sodium bicarbonate (target serum bicarb >22 mEq/L)",
    bp("Hypertension") + ": RAAS blockade + loop diuretics + CCBs",
    bp("Dyslipidemia") + ": statins",
]:
    story.append(bl(x))

story += [b("Renal Replacement Therapy (RRT) - Plan for GFR <15-20:")]
for x in [
    bp("Hemodialysis (HD)") + " - 3 sessions/week x 4-5 h; needs AV fistula (created 3-6 months before)",
    bp("Peritoneal dialysis (PD)") + " - CAPD or APD; home-based; peritoneum as dialysis membrane",
    bp("Kidney transplantation") + " - best option for eligible patients (see Topic 6)",
]:
    story.append(bl(x))

story += [b("Dental Relevance:")]
story += [p("(1) " + bp("Uremic platelet dysfunction") + " -> prolonged bleeding time -> significant bleeding risk after extractions; plan with nephrologist. "
    "(2) " + bp("Oral manifestations of CKD") + ": uremic stomatitis (mucosal ulceration/pseudomembrane), uremic fetor (ammonia smell), pallor (anemia), "
    "gingival bleeding, enamel hypoplasia in children, periodontal disease, jaw metastatic calcifications (secondary HPT). "
    "(3) " + bp("Drug dose adjustment") + " essential: metronidazole safe; amoxicillin dose-reduce in eGFR <10; avoid NSAIDs; avoid tetracycline. "
    "(4) Patients on dialysis - schedule dental treatment the day " + bp("after") + " HD (heparin effect wanes, patient optimally cleared). "
    "(5) AV fistula: do NOT take BP from fistula arm.")]

story.append(PageBreak())

# ============================================================
# TOPIC 5: KIDNEY FAILURE (ESKD)
# ============================================================
story += [topic_banner("KIDNEY FAILURE (End-Stage Renal Disease - ESKD)", "5"), sp(0.2)]

story += [section_box("Definition")]
story += [p("Kidney failure (ESKD / Stage G5 CKD) is defined as " + bp("GFR <15 mL/min/1.73m2") + " or dependence on "
    "renal replacement therapy (RRT) for survival. It is the final common endpoint of progressive CKD "
    "from any cause. Also termed " + bp("end-stage renal disease (ESRD)") + " or uremia.")]

story += [section_box("Features / Uremic Syndrome (see CKD - all features more pronounced)")]
story += [mk_table([
    [Paragraph(bp("System"), body_style), Paragraph(bp("Key Manifestations at ESKD Stage"), body_style)],
    [p("Cardiovascular"), p(bp("LVH, accelerated atherosclerosis") + " - leading cause of death in ESKD. "
        "Uremic pericarditis (pericardial friction rub - urgent dialysis indication). "
        "Increased risk of sudden cardiac death.")],
    [p("Hematological"), p(bp("Severe anemia") + " (Hb often <8 g/dL); "
        bp("Platelet dysfunction") + " - impaired aggregation (uremic toxins impair GP IIb/IIIa); "
        "Bleeding tendency (GI bleed, post-surgical bleeding).")],
    [p("Neurological"), p("Uremic encephalopathy (asterixis, confusion, seizures); "
        "peripheral neuropathy; dialysis disequilibrium syndrome (cerebral edema after rapid dialysis).")],
    [p("Bones"), p(bp("Renal osteodystrophy") + " - Osteitis fibrosa cystica (Brown tumors) from severe 2ndary HPT; "
        "pathological fractures; calciphylaxis (vascular calcification causing tissue necrosis).")],
    [p("Fluids/Electrolytes"), p("Hyperkalemia (life-threatening - arrhythmias); "
        "Hyperphosphatemia; Hypocalcemia; Metabolic acidosis (AG type); "
        "Fluid overload - hypertension, pulmonary edema.")],
    [p("GI"), p("Uremic fetor, anorexia, nausea, vomiting; uremic gastritis/peptic ulcers; "
        "malnutrition (protein-energy wasting).")],
    [p("Skin"), p("Pruritus (uremic itch - MC complaint); sallow yellow/grey discoloration; "
        "uremic frost (white urea crystals); purpura; ecchymoses.")],
], [3.5*cm, 13.5*cm]), sp()]

story += [section_box("Indications for RRT in ESKD (AEIOU mnemonic - same as AKI + chronic indications)")]
for x in [
    bp("A - Acidosis") + ": refractory metabolic acidosis (pH <7.1)",
    bp("E - Electrolytes") + ": refractory hyperkalemia (K >6.5 mEq/L, ECG changes)",
    bp("I - Intoxication") + ": uremic pericarditis, uremic encephalopathy, uremic bleeding (platelet dysfunction)",
    bp("O - Overload") + ": volume overload, pulmonary edema not responding to diuretics",
    bp("U - Uremia") + ": symptoms of uremia (encephalopathy, pericarditis, neuropathy)",
    bp("GFR <10 mL/min") + ": asymptomatic initiation in diabetics; <5 ml/min in non-diabetics",
]:
    story.append(bl(x))

story += [section_box("Renal Replacement Therapy Options")]
story += [mk_table([
    [Paragraph(bp("Modality"), body_style), Paragraph(bp("Mechanism"), body_style), Paragraph(bp("Advantages / Disadvantages"), body_style)],
    [p(bp("Hemodialysis (HD)")), p("Blood filtered through artificial kidney (dialyzer) using semipermeable membrane; solute removal by diffusion + ultrafiltration"), p(
        "3x/week x 4-5 h in center. Rapid solute clearance. Needs: AV fistula (preferred), AV graft, or central venous catheter. "
        "Heparin anticoagulation required. Risk: hypotension, cramps, infection.")],
    [p(bp("Peritoneal Dialysis (PD)")), p("Peritoneum as dialysis membrane; dialysate instilled via catheter; solutes diffuse across"), p(
        "CAPD: 4 exchanges/day. CCPD: automated overnight. "
        "Home-based, gentler, preserves residual renal function. "
        "Risk: peritonitis (MC complication), hyperglycemia, malnutrition.")],
    [p(bp("Kidney Transplantation")), p("Functioning donor kidney provides near-normal renal function"), p(
        "Best quality of life and survival. Requires lifelong immunosuppression. "
        "Risk: rejection, infections, malignancy. See Topic 6 for indications.")],
], [3.5*cm, 5*cm, 8.5*cm]), sp()]

story += [b("Dental Relevance in ESKD:")]
story += [p("(1) " + bp("Hemodialysis patients") + ": "
    "DO NOT take BP or perform venepuncture on AV fistula arm. "
    "Treat day-after HD (heparin cleared, stable electrolytes). "
    "Check Hb and platelets before extractions (severe anemia and platelet dysfunction). "
    "Heparin rebound may cause post-procedure bleeding. "
    "(2) " + bp("CAPD patients") + ": dental bacteremia may cause peritonitis - prophylactic antibiotics controversial but consider for high-risk procedures. "
    "(3) " + bp("Renal osteodystrophy") + ": Brown tumors (giant cell lesions) can appear in jaw - may mimic ameloblastoma or giant cell granuloma on OPG. "
    "(4) " + bp("Drug prescribing") + ": avoid NSAIDs, tetracyclines, nephrotoxic drugs. "
    "Amoxicillin, metronidazole, lignocaine: dose adjustment needed in ESKD. "
    "(5) Uremic fetor (ammonia breath smell); pallor, bleeding gums.")]

story.append(PageBreak())

# ============================================================
# TOPIC 6: INDICATIONS FOR LIVER AND KIDNEY TRANSPLANT
# ============================================================
story += [topic_banner("INDICATIONS FOR LIVER AND KIDNEY TRANSPLANT", "6"), sp(0.2)]

story += [section_box("KIDNEY TRANSPLANTATION")]
story += [p(bp("Definition") + ": Surgical placement of a functioning kidney from a donor (living or deceased/cadaveric) "
    "into a recipient with ESKD. The native kidneys are usually left in place. "
    "The transplant kidney is placed in the " + bp("iliac fossa") + " (heterotopic transplant).")]

story += [b("Indications for Kidney Transplantation:")]
story += [mk_table([
    [Paragraph(bp("Category"), body_style), Paragraph(bp("Conditions"), body_style)],
    [p("Diabetic Nephropathy"), p("Type 1 DM: simultaneous pancreas-kidney transplant (SPK) preferred. Type 2 DM: kidney alone.")],
    [p("Glomerulonephritis"), p("FSGS, IgA nephropathy, MPGN, lupus nephritis reaching ESKD")],
    [p("Hypertensive Nephrosclerosis"), p("Chronic hypertension leading to ESKD")],
    [p("Hereditary Disease"), p("ADPKD (MC genetic indication), Alport syndrome, cystinosis, oxalosis (combined liver-kidney)")],
    [p("Chronic Pyelonephritis / Reflux Nephropathy"), p("Recurrent UTI-related ESKD")],
    [p("Obstructive Uropathy"), p("After correction of obstruction; GFR does not recover to adequate levels")],
    [p("Congenital Anomalies"), p("Renal agenesis/hypoplasia, posterior urethral valves")],
    [p("Other CKD Causes"), p("Analgesic nephropathy, sickle cell nephropathy, systemic vasculitis")],
], [4.5*cm, 12.5*cm]), sp()]

story += [b("General Eligibility Criteria:")]
for x in [
    bp("GFR <15-20 mL/min") + " with irreversible renal failure (or dialysis-dependent)",
    "Good cardiovascular reserve and surgical fitness",
    "No active malignancy (cancer-free for 2-5 years depending on type)",
    "No active infection (must be treated before transplant)",
    "No active/untreated psychiatric illness",
    "No active substance abuse",
    "Compliance with medications and follow-up",
    "ABO blood group compatibility and cross-match negative",
]:
    story.append(bl(x))

story += [b("Absolute Contraindications to Kidney Transplant:")]
for x in [
    "Active untreated malignancy",
    "Active systemic infection (sepsis, active TB, HIV with poor control)",
    "Severe cardiac disease / irreversible cardiac failure",
    "Severe irreversible pulmonary disease",
    "Active autoimmune disease uncontrolled (SLE in flare)",
    "Positive cross-match (recipient has preformed antibodies against donor HLA)",
    "Chronic active hepatitis B/C with ongoing liver damage (unless combined liver-kidney)",
    "Non-compliance / active drug abuse",
]:
    story.append(bl(x))

story += [b("Sources of Donor Kidney:")]
story += [mk_table([
    [Paragraph(bp("Type"), body_style), Paragraph(bp("Details"), body_style), Paragraph(bp("Outcome"), body_style)],
    [p("Living Related Donor (LRD)"), p("Parent, sibling, child, spouse; voluntary donation after full workup"), p("Best outcomes; immediate function; shorter cold ischemia time")],
    [p("Living Unrelated Donor (LURD)"), p("Spouse, friend, altruistic donor"), p("Good outcomes; regulated by law to prevent organ trafficking")],
    [p("Deceased/Cadaveric Donor"), p("Brain-dead donor (DBD) or DCD (donation after circulatory death)"), p("Longer wait time; delayed graft function more common")],
], [3.5*cm, 7*cm, 6.5*cm]), sp()]

story += [b("Complications of Kidney Transplant:")]
story += [mk_table([
    [Paragraph(bp("Complication"), body_style), Paragraph(bp("Time"), body_style), Paragraph(bp("Details"), body_style)],
    [p(bp("Hyperacute rejection")), p("Minutes-hours"), p("ABO incompatibility or preformed antibodies; complement activation; thrombosis of graft vessels; graft must be removed")],
    [p(bp("Acute rejection")), p("Days-weeks (peak 5-14 days)"), p("T-cell mediated (cellular) or antibody-mediated; oliguria, graft tenderness, fever; treat with pulsed steroids/ATG/plasmapheresis")],
    [p(bp("Chronic rejection")), p("Months-years"), p("Insidious GFR decline; fibrosis; poorly responsive to treatment; main cause of late graft loss")],
    [p("Infections"), p("Early: bacterial. Late: CMV, PCP, fungal"), p("Due to lifelong immunosuppression; CMV prophylaxis with valganciclovir")],
    [p("Malignancy"), p("Years"), p("Skin cancers (MC), PTLD (post-transplant lymphoproliferative disorder - EBV-related)")],
    [p("CVS disease"), p("Ongoing"), p("MC cause of death with functioning graft")],
], [3.5*cm, 3.5*cm, 10*cm]), sp()]

story += [b("Immunosuppression Protocol:")]
for x in [
    bp("Induction") + ": Basiliximab (anti-IL2R) or anti-thymocyte globulin (ATG)",
    bp("Maintenance triple therapy") + ": Tacrolimus (calcineurin inhibitor) + Mycophenolate mofetil (MMF) + Low-dose prednisolone",
    "Alternative CNIs: Cyclosporine (causes gingival hyperplasia - dental relevance)",
    bp("mTOR inhibitors") + ": Sirolimus/Everolimus - used as alternatives; reduce malignancy risk",
]:
    story.append(bl(x))

story += [sp(), section_box("LIVER TRANSPLANTATION")]
story += [p(bp("Definition") + ": Replacement of a diseased liver with a healthy donor liver. "
    "Types: " + bp("Orthotopic liver transplant (OLT)") + " (MC - native liver removed and donor placed in same position); "
    "Living donor LT (LDLT) - partial liver from living donor; Split LT; Domino LT.")]

story += [b("Indications for Liver Transplantation:")]
story += [mk_table([
    [Paragraph(bp("Category"), body_style), Paragraph(bp("Specific Conditions"), body_style)],
    [p(bp("Chronic Liver Disease with End-Stage Failure") + "\n(MC indication overall)"),
     p("- " + bp("Cirrhosis from any cause") + " with complications (decompensation)\n"
        "- " + bp("Hepatitis C cirrhosis") + " - historically MC indication in Western countries\n"
        "- " + bp("Hepatitis B cirrhosis") + "\n"
        "- " + bp("Alcoholic liver disease (ALD)") + " - requires 6 months sobriety before listing\n"
        "- " + bp("Non-alcoholic steatohepatitis (NASH) / NAFLD cirrhosis") + " - now MC indication\n"
        "- Primary biliary cholangitis (PBC)\n"
        "- Primary sclerosing cholangitis (PSC)")],
    [p(bp("Acute Liver Failure (Fulminant Hepatic Failure)")),
     p("- Drug-induced ALF: " + bp("Paracetamol overdose (MC cause of ALF in UK)") + "\n"
        "- Acute hepatitis A, B (fulminant)\n"
        "- Wilson's disease (acute)\n"
        "- Budd-Chiari syndrome (acute)\n"
        "- Indeterminate ALF\n"
        "- Listed using " + bp("King's College Criteria") + " for prognosis")],
    [p(bp("Hepatocellular Carcinoma (HCC)")),
     p(bp("Milan Criteria") + " for listing: Single lesion <=5 cm OR up to 3 lesions each <=3 cm, "
        "no vascular invasion, no extrahepatic spread. "
        "Extended criteria: UCSF criteria.")],
    [p(bp("Metabolic / Genetic Liver Disease")),
     p("- Wilson's disease (chronic)\n"
        "- Alpha-1 antitrypsin deficiency\n"
        "- Hereditary hemochromatosis\n"
        "- Glycogen storage disorders\n"
        "- Crigler-Najjar syndrome type 1 (biliary)\n"
        "- Oxalosis (combined liver-kidney)")],
    [p("Cholestatic Liver Disease"),
     p("Primary biliary cholangitis (PBC), Primary sclerosing cholangitis (PSC), biliary atresia (MC indication in children - Kasai operation failure)")],
    [p("Retransplantation"), p("Chronic rejection (hepatic artery thrombosis), primary non-function of graft, recurrent disease")],
], [5*cm, 12*cm]), sp()]

story += [b("Severity Scoring - MELD Score (Model for End-stage Liver Disease):")]
story += [p(bp("MELD score") + " = 10 x [0.957 x ln(Creatinine) + 0.378 x ln(Bilirubin) + 1.12 x ln(INR)] + 6.43. "
    "Score 6-40; higher = worse prognosis; " + bp("MELD >=15") + " = benefit from transplant outweighs surgical risk. "
    "Used to prioritize patients on the waiting list. "
    bp("Child-Pugh score") + " also used: parameters = encephalopathy, ascites, bilirubin, albumin, PT.")]

story += [b("Absolute Contraindications to Liver Transplant:")]
for x in [
    "Active extrahepatic malignancy",
    "Active uncontrolled infection / sepsis",
    "Severe cardiopulmonary disease (unable to survive surgery)",
    "Active alcohol / substance abuse (must be abstinent for min 6 months for ALD)",
    "Uncontrolled psychiatric disease or non-compliance",
    "AIDS (relative - but HIV+ve now acceptable at many centers with good CD4)",
    "Anatomical contraindications (extensive portal vein thrombosis in some)",
]:
    story.append(bl(x))

story += [b("Complications of Liver Transplant:")]
story += [mk_table([
    [Paragraph(bp("Complication"), body_style), Paragraph(bp("Details"), body_style)],
    [p("Primary non-function (PNF)"), p("Graft fails immediately post-transplant; requires urgent retransplantation")],
    [p("Hepatic artery thrombosis (HAT)"), p("MC vascular complication; graft ischemia; biliary necrosis")],
    [p("Rejection (acute/chronic)"), p("Acute: raised LFTs at day 5-10; treat with steroids. Chronic: vanishing bile duct syndrome")],
    [p("Infections"), p("Bacterial (early), CMV (commonest viral - 2-6 weeks), fungal (Candida, Aspergillus)")],
    [p("Recurrent disease"), p("Recurrence of HCV (universal before DAAs), HBV, NASH, HCC, PBC, PSC")],
    [p("Biliary complications"), p("Bile leak, biliary strictures - most common technical complication")],
], [4.5*cm, 12.5*cm]), sp()]

story += [b("Dental Relevance - Transplant Patients (Kidney and Liver):")]
story += [p("(1) " + bp("Immunosuppression") + " causes severe infection risk and impaired wound healing - "
    "plan dental treatment carefully; use prophylactic antibiotics for invasive procedures (per protocol). "
    "(2) " + bp("Cyclosporine-induced gingival overgrowth") + " - common (30-50% of patients); "
    "can be severe; requires meticulous oral hygiene and regular dental review; surgical gingivectomy if needed. "
    "(3) " + bp("Tacrolimus") + " - check drug levels before procedures (many dental drugs alter tacrolimus levels). "
    "Clarithromycin, fluconazole, metronidazole " + bp("raise tacrolimus levels") + " (CYP3A4 inhibition) - risk of toxicity and rejection. "
    "(4) " + bp("Steroid-induced adrenal suppression") + " - double steroid dose on day of stressful dental procedure. "
    "(5) Increased risk of " + bp("oral candidiasis, HSV stomatitis, HPV-related oral lesions, PTLD lymphoma") + ". "
    "(6) Anticoagulation: tacrolimus and mycophenolate can affect platelets; check CBC + PT. "
    "(7) " + bp("INR monitoring") + " important in post-transplant patients on warfarin.")]

# FOOTER
story += [sp(0.3), HRFlowable(width="100%", thickness=1, color=colors.HexColor('#ce93d8')), sp(0.2),
    Paragraph("General Medicine Short Notes | BDS 3rd Year | Gujarat University | "
        "Based on Anil K. Tripathi - General Medicine for BDS | Part 3: Nephrology & Transplantation",
        footer_style)]

doc.build(story)
print("PDF generated successfully!")
Running Command

cd /tmp/workspace/bds-notes && python3 generate_notes3.py 2>&1

Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.