Answer all questions from apporva shastribook for professional exam
python3 -c " from pypdf import PdfReader reader = PdfReader('/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/Microbiology_Paper_1.pdf') print(f'Pages: {len(reader.pages)}') for i, page in enumerate(reader.pages): print(f'--- PAGE {i+1} ---') print(page.extract_text()) "
| Feature | Prokaryotes | Eukaryotes |
|---|---|---|
| Nucleus | No true nucleus; nucleoid only | True membrane-bound nucleus |
| Membrane organelles | Absent (no mitochondria, ER, Golgi) | Present (mitochondria, ER, Golgi) |
| Ribosome size | 70S (50S + 30S subunits) | 80S (60S + 40S subunits) |
| Cell wall | Present; contains peptidoglycan (murein) | Absent or lacks peptidoglycan |
| DNA | Single circular chromosome, no histones | Multiple linear chromosomes with histones |
| Examples | Bacteria, Archaea | Fungi, protozoa, human cells |
Log (CFU)
| ___________
| / \
| / \
| _________/ \____________
|______/
+-----+--------+------------+-------+---------> Time
Lag Log Stationary Decline
Phase Phase Phase Phase
| Feature | Gram-Positive | Gram-Negative |
|---|---|---|
| Peptidoglycan | Thick (multilayer) | Thin (single layer) |
| Outer membrane | Absent | Present |
| Teichoic acids | Present | Absent |
| LPS (endotoxin) | Absent | Present |
| Periplasmic space | Narrow | Wide |
| Susceptibility to penicillin | More susceptible | Less susceptible |
| Feature | Mutational Resistance | Plasmid-mediated (R-factor) Resistance |
|---|---|---|
| Mechanism | Spontaneous mutation in chromosomal gene | Genes on extrachromosomal plasmid (R-factor/R-plasmid) |
| Transfer | Not transferable between bacteria | Transferable by conjugation, transduction, transformation |
| Number of drugs | Usually to single drug (one-step) | Often to multiple drugs simultaneously |
| Speed of emergence | Slow (random mutation) | Can be rapid (epidemic spread) |
| Example organisms | M. tuberculosis (INH resistance), E. coli | E. coli, Staphylococcus, Klebsiella |
| Clinical significance | Gradual, use combination therapy | Major cause of hospital-acquired MDR infections |
| Feature | S. pneumoniae | S. viridans (e.g., S. mutans, S. mitis) |
|---|---|---|
| Morphology | Lancet-shaped diplococcus | Oval/round cocci in chains |
| Bile solubility | Positive (bile dissolves capsule) | Negative |
| Optochin sensitivity | Sensitive (inhibited by optochin) | Resistant |
| Capsule | Present (polysaccharide) | Usually absent |
| Quellung reaction | Positive | Negative |
| Inulin fermentation | Positive | Variable |
| Virulence | Highly virulent; causes lobar pneumonia, meningitis | Low virulence; opportunist in damaged valves |
| Diseases | Pneumonia, meningitis, otitis media | Subacute bacterial endocarditis (SBE), dental caries |
| Week | Specimen | Test |
|---|---|---|
| Week 1 | Blood | Blood culture (positive in 80-90% of cases) |
| Week 2 | Urine, Stool | Urine culture, stool culture; Widal test rising titre |
| Week 3 | Stool, Urine | Stool and urine cultures; Widal test high titre |
| Week 4+ | Stool | Stool culture; Widal test diagnostic |
| Feature | Classical Biotype | El Tor Biotype |
|---|---|---|
| Voges-Proskauer test | Negative | Positive |
| Haemolysis (sheep RBCs) | Negative (Haemolytic el Tor strains) | Positive (most El Tor) |
| Agglutination of chicken RBCs | Negative | Positive |
| Polymyxin B sensitivity | Sensitive | Resistant |
| Phage susceptibility | Type IV phage | Type V phage (El Tor phage) |
| Disease severity | More severe disease | Milder; more asymptomatic carriers |
| Epidemics | Caused earlier pandemic (1-6th) | Responsible for 7th pandemic (ongoing) |
| Survival | Less stable | More stable in environment |
| Serovars | Disease |
|---|---|
| A, B, Ba, C | Trachoma (leading cause of preventable blindness) |
| D-K | Genital tract infections: urethritis, cervicitis, PID; Neonatal conjunctivitis; Inclusion conjunctivitis in adults |
| L1, L2, L3 | Lymphogranuloma Venereum (LGV) - painless genital ulcer → inguinal buboes → rectal stricture |
| Feature | Chlamydia | Viruses |
|---|---|---|
| Cell wall | Present (but no peptidoglycan - no muramic acid) | Absent |
| Ribosomes | Present (70S) | Absent |
| Binary fission | Yes (divides by binary fission) | No (replication by host machinery) |
| DNA AND RNA | Both present | Either DNA or RNA |
| Metabolic activity | Has own metabolism (but energy parasite) | No independent metabolism |
| Size | Larger (300-1000 nm) | Smaller (viruses: 20-300 nm) |
| Antibiotic sensitivity | Sensitive (tetracycline, erythromycin) | Not sensitive to antibiotics |
| Intracellular | Obligate intracellular | Obligate intracellular |
| Species | Serogroup | Key features |
|---|---|---|
| S. dysenteriae | A | Type 1 produces Shiga toxin (most virulent) |
| S. flexneri | B | Most common worldwide |
| S. boydii | C | |
| S. sonnei | D | Mildest, most common in developed countries |
| Species | X factor | V factor |
|---|---|---|
| H. influenzae | + | + |
| H. parainfluenzae | - | + |
| H. ducreyi | + | - |
| H. aphrophilus | + | - |
Blood agar plate:
[Staphylococcus streak] - - - - - - >
. . large H. flu . . . . small/no growth
| Pathotype | Mechanism | Disease | Lab Test |
|---|---|---|---|
| ETEC | LT/ST toxins | Traveler's diarrhea, watery | ELISA for LT/ST; Y1 adrenal cell assay; PCR |
| EPEC | Attaching/effacing lesions (LEE pathogenicity island) | Infantile diarrhea (developing world) | HEp-2 cell adhesion assay; PCR |
| EIEC | Invasion of colon (like Shigella) | Dysentery-like illness | Sereny test (guinea pig keratoconjunctivitis); PCR |
| EHEC (O157:H7) | Shiga-like toxin (Stx1, Stx2) | Bloody diarrhea, HUS | Sorbitol-MacConkey agar (SMAC) - EHEC doesn't ferment sorbitol; ELISA for Stx; PCR |
| EAEC | Aggregative adherence (stacked brick pattern) | Persistent diarrhea | HEp-2 cell adherence (AA pattern); PCR |
| Group | Characteristics | Examples |
|---|---|---|
| Group I - Photochromogens | Slow-growing; produce pigment ONLY in light | M. kansasii, M. marinum |
| Group II - Scotochromogens | Slow-growing; produce pigment in BOTH light and dark | M. scrofulaceum, M. gordonae |
| Group III - Non-chromogens | Slow-growing; NO pigment | M. avium-intracellulare (MAC), M. ulcerans (Buruli ulcer) |
| Group IV - Rapid growers | Fast-growing (< 7 days); may or may not produce pigment | M. fortuitum, M. chelonae |
| Feature | Tuberculoid Leprosy (TT) | Lepromatous Leprosy (LL) |
|---|---|---|
| Immunity (CMI) | Good cell-mediated immunity | Poor CMI; high humoral antibody |
| Skin lesions | Few (1-3), well-defined, hypopigmented, anesthetic, raised borders | Many, diffuse, symmetrical, poorly-defined, not anesthetic (at first) |
| Nerve involvement | Thick, palpable peripheral nerves; asymmetric | Symmetric; less thickened initially |
| Lepromin test | Positive (strong CMI) | Negative (anergic) |
| Bacillary load (BI) | Paucibacillary (BI 0-1+) | Multibacillary (BI 4-6+); globi in macrophages |
| Histology | Well-formed epithelioid granulomas | Foamy (Virchow) macrophages loaded with bacilli |
| Genus | Species | Disease |
|---|---|---|
| Treponema | T. pallidum ssp pallidum | Syphilis |
| T. pallidum ssp endemicum | Bejel (endemic syphilis) | |
| T. pallidum ssp pertenue | Yaws | |
| T. carateum | Pinta | |
| Borrelia | B. recurrentis | Louse-borne relapsing fever |
| B. duttoni | Tick-borne relapsing fever | |
| B. burgdorferi | Lyme disease | |
| Leptospira | L. interrogans | Leptospirosis |
| Week | Positive Test |
|---|---|
| Week 1 | Blood culture (90%), bone marrow culture (highest sensitivity, even in partially treated) |
| Week 2 | Widal test becomes positive; stool and urine cultures turn positive |
| Week 3 | Stool culture +; Widal test at peak; complication week |
| Week 4+ | Stool culture +; Widal declining |
| Colour | Container | Waste Type |
|---|---|---|
| Yellow | Non-chlorinated plastic bag | Human anatomical waste, animal waste, pathological waste, blood-soaked items, expired medicines, chemical/pharmaceutical waste |
| Red | Non-chlorinated plastic bag | Contaminated recyclable waste: IV tubing, syringes (without needles), gloves, catheters, blood bags |
| White (Translucent) | Puncture-proof, leak-proof sharps container | Needles, syringes with fixed needles, lancets, scalpels, broken glass |
| Blue | Puncture-proof, leak-proof box | Glassware - broken or discarded, metallic implants |
| Zoonosis | Causative Agent | Animal Reservoir |
|---|---|---|
| Rabies | Rabies virus (Rhabdovirus) | Dogs, bats, foxes |
| Brucellosis | Brucella abortus/melitensis | Cattle, goats, sheep |
| Leptospirosis | Leptospira interrogans | Rats, dogs, cattle |
| Plague | Yersinia pestis | Rats (flea vector) |
| Anthrax | Bacillus anthracis | Cattle, sheep, goats |
| Q fever | Coxiella burnetii | Cattle, sheep |
| Test | Pyogenic Meningitis | Normal |
|---|---|---|
| Appearance | Turbid/purulent | Clear |
| Cells | >500 cells/mm³, PMN predominance | 0-5 lymphocytes |
| Protein | Markedly elevated (>100 mg/dL) | 15-45 mg/dL |
| Glucose | Decreased (<40 mg/dL, <50% serum) | 45-70 mg/dL |
| Pressure | Elevated | Normal |
| Condition | Organisms |
|---|---|
| Community-acquired pneumonia (CAP) | S. pneumoniae (most common), H. influenzae, M. catarrhalis, K. pneumoniae, S. aureus |
| Atypical pneumonia | Mycoplasma pneumoniae, Legionella pneumophila, Chlamydia pneumoniae |
| Hospital-acquired pneumonia (HAP/VAP) | P. aeruginosa, Klebsiella, Acinetobacter, MRSA, Enterobacter |
| Whooping cough (pertussis) | Bordetella pertussis |
| TB | Mycobacterium tuberculosis |
| Lung abscess/aspiration pneumonia | Anaerobes (Peptostreptococcus, Prevotella, Fusobacterium, Bacteroides) |
| Immunocompromised | PCP (Pneumocystis jirovecii), Nocardia, M. avium complex |
| Age | Common Organisms |
|---|---|
| Neonates | Group B Streptococcus (S. agalactiae), E. coli, Listeria monocytogenes |
| Infants (1-3 months) | GBS, E. coli, H. influenzae, S. pneumoniae, N. meningitidis |
| Children (3 months - 5 years) | S. pneumoniae, N. meningitidis, H. influenzae type b (pre-vaccine) |
| Adults | S. pneumoniae (most common), N. meningitidis |
| Elderly/immunocompromised | S. pneumoniae, Listeria monocytogenes, Gram-negative bacilli |
| Post-neurosurgery | S. aureus, Gram-negative bacilli (Pseudomonas, Klebsiella) |
| Disease | Organism |
|---|---|
| Gonorrhea | Neisseria gonorrhoeae |
| Syphilis | Treponema pallidum |
| Chlamydia/NGU | Chlamydia trachomatis (D-K) |
| LGV | C. trachomatis (L1-L3) |
| Chancroid | Haemophilus ducreyi |
| Donovanosis (Granuloma inguinale) | Klebsiella granulomatis (Calymmatobacterium) |
| Bacterial vaginosis | Gardnerella vaginalis, anaerobes |
| Trichomoniasis | Trichomonas vaginalis (protozoan) |
| Genital herpes | HSV-2 (and HSV-1) |
| Genital warts | HPV (types 6, 11 - warts; 16, 18 - cancer) |
| HIV/AIDS | HIV-1, HIV-2 |
| Hepatitis B | Hepatitis B virus |
| Organism | Type | Incubation |
|---|---|---|
| S. aureus | Preformed toxin (emetic) | 1-6 hours |
| B. cereus (emetic) | Preformed cereulide toxin (rice) | 1-6 hours |
| C. perfringens type A | Enterotoxin formed in gut | 8-24 hours |
| B. cereus (diarrheal) | LT-like enterotoxin | 8-16 hours |
| C. botulinum | Preformed neurotoxin | 12-36 hours |
| Salmonella (non-typhoidal) | Invasive + enterotoxin | 12-48 hours |
| V. parahaemolyticus | TDH enterotoxin | 4-96 hours (mean 12) |
| E. coli ETEC | LT/ST enterotoxin | 8-24 hours |
| Campylobacter jejuni | Invasive | 48-72 hours |
| Feature | Exotoxin | Endotoxin |
|---|---|---|
| Source | Secreted by BOTH Gram-positive and Gram-negative bacteria (mostly Gram+) | Cell wall component of Gram-negative bacteria (Lipid A of LPS) |
| Chemical nature | Protein (polypeptide) | Lipopolysaccharide (Lipid A is the toxic moiety) |
| Heat stability | Heat-labile (usually destroyed at 60-80°C in 30 min) | Heat-stable (withstands 160°C dry heat) |
| Antigenicity | Highly antigenic; can be converted to toxoid (formaldehyde treatment) | Weakly antigenic; CANNOT be converted to toxoid |
| Toxicity | High specific toxicity (nanogram quantities lethal) | Low specific toxicity; requires large doses |
| Mode of action | Specific (each has defined mechanism: ADP-ribosylation, pore formation, etc.) | Non-specific: triggers cytokine storm (TNF, IL-1, IL-6) → fever, shock, DIC |
| Examples | Tetanospasmin, diphtheria toxin, botulinum toxin, cholera toxin | Salmonella, E. coli, N. meningitidis LPS |
Keep all the information intact and compress this pdf into less pages for quick exam revision and also make it little attractive with color lines and boxes for easy revison
python3 -c " from pypdf import PdfReader reader = PdfReader('/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/72be89f6-8ad4-4b8b-95c8-a4223a8a1a3a (1).pdf') print(f'Pages: {len(reader.pages)}') for i, page in enumerate(reader.pages[:3]): print(f'--- PAGE {i+1} ---') print(page.extract_text()[:2000]) print() "
python3 -c " from pypdf import PdfReader reader = PdfReader('/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/72be89f6-8ad4-4b8b-95c8-a4223a8a1a3a (1).pdf') full_text = '' for i, page in enumerate(reader.pages): full_text += page.extract_text() + '\n' print(f'Total chars: {len(full_text)}') # Save extracted text with open('/home/daytona/workspace/micro_text.txt', 'w') as f: f.write(full_text) print('Saved.') "
Keep all the information intact and compress this pdf into less pages for quick exam revision and also make it little attractive with color lines and boxes for easy revison
python3 -c " from pypdf import PdfReader path = '/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/72be89f6-8ad4-4b8b-95c8-a4223a8a1a3a (1) (1).pdf' reader = PdfReader(path) print(f'Pages: {len(reader.pages)}') full_text = '' for page in reader.pages: full_text += page.extract_text() + '\n' print(f'Total chars: {len(full_text)}') with open('/home/daytona/workspace/micro_raw.txt', 'w') as f: f.write(full_text) print('Done') "
Fast
ls /home/daytona/workspace/
cat << 'PYEOF' > /home/daytona/workspace/build_revision_pdf.py from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, KeepTogether) from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_LEFT, TA_CENTER from reportlab.platypus.flowables import BalancedColumns import re # ── Colour palette ────────────────────────────────────────────────────────── C_NAVY = colors.HexColor('#1a237e') C_TEAL = colors.HexColor('#00695c') C_PURPLE = colors.HexColor('#6a1b9a') C_ORANGE = colors.HexColor('#e65100') C_RED = colors.HexColor('#b71c1c') C_LBLUE = colors.HexColor('#e3f2fd') # light-blue fill C_LGREEN = colors.HexColor('#e8f5e9') # light-green fill C_LYELL = colors.HexColor('#fffde7') # light-yellow fill C_LPURP = colors.HexColor('#f3e5f5') # light-purple fill C_LGREY = colors.HexColor('#f5f5f5') W, H = A4 MARGIN = 12*mm # ── Styles ─────────────────────────────────────────────────────────────────── def make_styles(): base = dict(fontName='Helvetica', fontSize=7.5, leading=10, spaceAfter=1) s = {} s['title'] = ParagraphStyle('title', fontName='Helvetica-Bold', fontSize=13, leading=16, textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=4) s['h1'] = ParagraphStyle('h1', fontName='Helvetica-Bold', fontSize=9.5, leading=12, textColor=colors.white, backColor=C_NAVY, borderPadding=(3,6,3,6), spaceAfter=3, spaceBefore=6) s['h2'] = ParagraphStyle('h2', fontName='Helvetica-Bold', fontSize=8.5, leading=11, textColor=colors.white, backColor=C_TEAL, borderPadding=(2,5,2,5), spaceAfter=2, spaceBefore=4) s['h3'] = ParagraphStyle('h3', fontName='Helvetica-Bold', fontSize=8, leading=10.5, textColor=C_PURPLE, spaceAfter=1, spaceBefore=3) s['body'] = ParagraphStyle('body', **base) s['bullet'] = ParagraphStyle('bullet', fontName='Helvetica', fontSize=7.5, leading=10, leftIndent=8, firstLineIndent=0, spaceAfter=0.5, bulletIndent=2) s['key'] = ParagraphStyle('key', fontName='Helvetica-Bold', fontSize=7.5, leading=10, textColor=C_RED) return s ST = make_styles() # ── Helper – coloured box paragraph ───────────────────────────────────────── def box_para(text, bg=C_LBLUE, text_color=C_NAVY): style = ParagraphStyle('bp', fontName='Helvetica', fontSize=7.5, leading=10, backColor=bg, textColor=text_color, borderPadding=(2,4,2,4), spaceAfter=2) return Paragraph(text, style) # ── Parse the raw text into structured sections ────────────────────────────── def parse_text(raw): """Return list of (kind, text) tuples: kind = 'h1','h2','h3','bullet','body','table_row','hr' """ items = [] for line in raw.splitlines(): s = line.strip() if not s: continue # markdown headings if s.startswith('# ') and not s.startswith('## '): items.append(('h1', s[2:].strip())) elif s.startswith('## ') and not s.startswith('### '): items.append(('h2', s[3:].strip())) elif s.startswith('### '): items.append(('h3', s[4:].strip())) elif s.startswith('---'): items.append(('hr', '')) elif re.match(r'^\|.+\|', s): # table row cells = [c.strip() for c in s.split('|') if c.strip()] if cells and not re.match(r'^[-:]+$', cells[0]): items.append(('table_row', cells)) elif re.match(r'^(\d+\.|[-*•]) ', s): # bullet / numbered list text = re.sub(r'^(\d+\.|[-*•]) ', '', s) text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text) items.append(('bullet', '• ' + text)) else: text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', s) items.append(('body', text)) return items # ── Convert parsed items → ReportLab flowables ────────────────────────────── def build_flowables(items): flowables = [] # Cover title flowables.append(Spacer(1, 4*mm)) flowables.append(Paragraph('MICROBIOLOGY – QUICK REVISION', ST['title'])) flowables.append(Paragraph('<font color="#00695c"><b>Apurva Shastri | Professional Exam Answers</b></font>', ParagraphStyle('sub', fontName='Helvetica', fontSize=8.5, leading=11, alignment=TA_CENTER, spaceAfter=4))) flowables.append(HRFlowable(width='100%', thickness=2, color=C_NAVY, spaceAfter=5)) # group consecutive table_rows into tables i = 0 while i < len(items): kind, text = items[i] if kind == 'h1': flowables.append(Spacer(1, 2)) p = Paragraph(f' {text}', ST['h1']) flowables.append(p) i += 1 elif kind == 'h2': flowables.append(Spacer(1, 1)) p = Paragraph(f' {text}', ST['h2']) flowables.append(p) i += 1 elif kind == 'h3': # orange left-border effect via colored text p = Paragraph(f'<font color="#e65100">▌</font> <b>{text}</b>', ST['h3']) flowables.append(p) i += 1 elif kind == 'hr': flowables.append(HRFlowable(width='100%', thickness=0.5, color=colors.HexColor('#bdbdbd'), spaceAfter=1, spaceBefore=1)) i += 1 elif kind == 'bullet': flowables.append(Paragraph(text, ST['bullet'])) i += 1 elif kind == 'table_row': # collect all consecutive table rows rows = [] while i < len(items) and items[i][0] == 'table_row': rows.append(items[i][1]) i += 1 if not rows: continue # determine col widths ncols = max(len(r) for r in rows) avail = W - 2*MARGIN col_w = [avail / ncols] * ncols # build table data with styled paragraphs header_style = ParagraphStyle('th', fontName='Helvetica-Bold', fontSize=6.8, leading=9, textColor=colors.white) cell_style = ParagraphStyle('td', fontName='Helvetica', fontSize=6.8, leading=9) tdata = [] for ri, row in enumerate(rows): # pad row while len(row) < ncols: row.append('') if ri == 0: tdata.append([Paragraph(c, header_style) for c in row]) else: tdata.append([Paragraph(c, cell_style) for c in row]) t = Table(tdata, colWidths=col_w, repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), C_TEAL), ('BACKGROUND', (0,1), (-1,-1), C_LGREY), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, C_LGREY]), ('GRID', (0,0), (-1,-1), 0.3, colors.HexColor('#90a4ae')), ('LEFTPADDING', (0,0), (-1,-1), 3), ('RIGHTPADDING', (0,0), (-1,-1), 3), ('TOPPADDING', (0,0), (-1,-1), 2), ('BOTTOMPADDING', (0,0), (-1,-1), 2), ('VALIGN', (0,0), (-1,-1), 'TOP'), ])) flowables.append(t) flowables.append(Spacer(1, 2)) else: # body # detect key-value patterns like "Feature: explanation" if text.startswith('<b>') and ':' not in text[:40]: flowables.append(Paragraph(text, ST['key'])) else: flowables.append(Paragraph(text, ST['body'])) i += 1 return flowables # ── Main ───────────────────────────────────────────────────────────────────── with open('/home/daytona/workspace/micro_raw.txt') as f: raw = f.read() items = parse_text(raw) flowables = build_flowables(items) out = '/home/daytona/workspace/Microbiology_Revision_Compressed.pdf' doc = SimpleDocTemplate(out, pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=10*mm, bottomMargin=10*mm) doc.build(flowables) print('Done:', out) import os size = os.path.getsize(out) print(f'File size: {size/1024:.1f} KB') PYEOF python3 /home/daytona/workspace/build_revision_pdf.py
python3 -c " from pypdf import PdfReader r = PdfReader('/home/daytona/workspace/Microbiology_Revision_Compressed.pdf') print(f'Pages in output: {len(r.pages)}') "
Microbiology Revision Compressed
PDF Document · PDF
Compress in 5-6 pages
python3 -c " from pypdf import PdfReader reader = PdfReader('/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/DOC-20260713-WA0000..pdf') print(f'Pages: {len(reader.pages)}') full_text = '' for page in reader.pages: full_text += page.extract_text() + '\n' print(f'Total chars: {len(full_text)}') with open('/home/daytona/workspace/doc_raw.txt', 'w') as f: f.write(full_text) print(full_text[:3000]) "
cat << 'PYEOF' > /home/daytona/workspace/build_ultra_compact.py from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, KeepTogether) from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_LEFT, TA_CENTER from reportlab.platypus.flowables import Flowable import re, textwrap W, H = A4 MARGIN = 8*mm COL_GAP = 4*mm COL_W = (W - 2*MARGIN - COL_GAP) / 2 # ── Colours ────────────────────────────────────────────────────────────────── C_NAVY = colors.HexColor('#1a237e') C_TEAL = colors.HexColor('#006064') C_ORANGE = colors.HexColor('#bf360c') C_GREEN = colors.HexColor('#1b5e20') C_PURPLE = colors.HexColor('#4a148c') C_RED = colors.HexColor('#b71c1c') C_LBLUE = colors.HexColor('#e3f2fd') C_LGREEN = colors.HexColor('#e8f5e9') C_LYELL = colors.HexColor('#fffff0') C_LGREY = colors.HexColor('#f5f5f5') C_LTEAL = colors.HexColor('#e0f7fa') # Section colours cycle SEC_COLORS = [C_NAVY, C_TEAL, C_GREEN, C_PURPLE, C_ORANGE, C_RED, colors.HexColor('#004d40'), colors.HexColor('#311b92')] sec_idx = [0] # ── Styles ─────────────────────────────────────────────────────────────────── FS = 5.8 # base font size LD = 7.2 # base leading def S(name, **kw): defaults = dict(fontName='Helvetica', fontSize=FS, leading=LD, spaceAfter=0.5, spaceBefore=0) defaults.update(kw) return ParagraphStyle(name, **defaults) ST = { 'title': S('title', fontName='Helvetica-Bold', fontSize=9, leading=11, textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=2), 'sub': S('sub', fontSize=6.5, leading=8, alignment=TA_CENTER, textColor=C_TEAL, spaceAfter=2), 'h1': S('h1', fontName='Helvetica-Bold', fontSize=7, leading=8.5, textColor=colors.white, backColor=C_NAVY, borderPadding=(1.5,4,1.5,4), spaceAfter=1, spaceBefore=3), 'h2': S('h2', fontName='Helvetica-Bold', fontSize=6.2, leading=7.5, textColor=colors.white, backColor=C_TEAL, borderPadding=(1,3,1,3), spaceAfter=1, spaceBefore=2), 'h3': S('h3', fontName='Helvetica-Bold', fontSize=5.8, leading=7, textColor=C_NAVY, spaceAfter=0.5, spaceBefore=1.5), 'body': S('body'), 'bullet':S('bullet', leftIndent=7, firstLineIndent=0, spaceAfter=0.3), 'key': S('key', fontName='Helvetica-Bold', textColor=C_RED), } def clean(t): t = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', t) t = re.sub(r'`(.+?)`', r'<font name="Courier">\1</font>', t) return t # ── Parse ──────────────────────────────────────────────────────────────────── def parse(raw): items = [] for line in raw.splitlines(): s = line.strip() if not s: continue if s.startswith('# ') and not s.startswith('## '): items.append(('h1', s[2:].strip())) elif s.startswith('## ') and not s.startswith('### '): items.append(('h2', s[3:].strip())) elif s.startswith('### '): items.append(('h3', s[4:].strip())) elif s == '---': continue # skip dividers - saves space elif re.match(r'^\|.+\|', s): cells = [c.strip() for c in s.split('|') if c.strip()] if cells and not re.match(r'^[-:]+$', cells[0]): items.append(('tr', cells)) elif re.match(r'^[•\-\*] ', s) or re.match(r'^\d+\. ', s): text = re.sub(r'^[•\-\*\d]+\.?\s*', '', s) items.append(('bullet', '• ' + clean(text))) else: items.append(('body', clean(s))) return items # ── Build two-column page layout ───────────────────────────────────────────── # We'll use a 2-column Table as the page layout container def build_two_col(items): """Build all flowables into left/right column content lists, then stack as 2-col tables per page-worth.""" def make_flowable(kind, text): if kind == 'h1': c = sec_idx[0] % len(SEC_COLORS) sec_idx[0] += 1 st = ParagraphStyle('h1x', fontName='Helvetica-Bold', fontSize=7, leading=8.5, textColor=colors.white, backColor=SEC_COLORS[c], borderPadding=(1.5,4,1.5,4), spaceAfter=1, spaceBefore=3) return Paragraph(f' {text}', st) elif kind == 'h2': return Paragraph(f' {text}', ST['h2']) elif kind == 'h3': return Paragraph(f'<font color="#bf360c">▌</font> <b>{text}</b>', ST['h3']) elif kind == 'bullet': return Paragraph(text, ST['bullet']) else: return Paragraph(text, ST['body']) flowables = [] i = 0 while i < len(items): kind, text = items[i] if kind == 'tr': # collect table rows rows = [] while i < len(items) and items[i][0] == 'tr': rows.append(items[i][1]) i += 1 if not rows: continue ncols = max(len(r) for r in rows) # trim col widths to fit in a column avail = COL_W - 4 col_w = [avail / ncols] * ncols th_st = ParagraphStyle('th', fontName='Helvetica-Bold', fontSize=5, leading=6.2, textColor=colors.white) td_st = ParagraphStyle('td', fontName='Helvetica', fontSize=5, leading=6.2) tdata = [] for ri, row in enumerate(rows): while len(row) < ncols: row.append('') row = row[:ncols] if ri == 0: tdata.append([Paragraph(c, th_st) for c in row]) else: tdata.append([Paragraph(c, td_st) for c in row]) t = Table(tdata, colWidths=col_w, repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), C_TEAL), ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, C_LGREY]), ('GRID', (0,0), (-1,-1), 0.25, colors.HexColor('#b0bec5')), ('LEFTPADDING', (0,0), (-1,-1), 2), ('RIGHTPADDING', (0,0), (-1,-1), 2), ('TOPPADDING', (0,0), (-1,-1), 1), ('BOTTOMPADDING', (0,0), (-1,-1), 1), ('VALIGN', (0,0), (-1,-1), 'TOP'), ])) flowables.append(t) flowables.append(Spacer(1, 1.5)) else: flowables.append(make_flowable(kind, text)) i += 1 return flowables # ── Main ───────────────────────────────────────────────────────────────────── with open('/home/daytona/workspace/doc_raw.txt') as f: raw = f.read() items = parse(raw) # Build single-column flowables first, then put into 2-col frame table all_fl = build_two_col(items) # Use BalancedColumns / manual 2-col Table approach # Split flowables into ~equal halves per page group using a 2-col table # with each cell containing a sub-story # Simpler reliable approach: use a 2-column table where each row has # left_content | right_content, flushed together. # Best approach for guaranteed 5-6 pages: use Frame-based doc from reportlab.platypus import Frame, PageTemplate, BaseDocTemplate from reportlab.platypus.frames import Frame as RLFrame class TwoColDoc(BaseDocTemplate): def __init__(self, filename, **kw): super().__init__(filename, **kw) # Two frames side by side f_left = RLFrame(MARGIN, MARGIN + 5*mm, COL_W, H - 2*MARGIN - 8*mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='left') f_right = RLFrame(MARGIN + COL_W + COL_GAP, MARGIN + 5*mm, COL_W, H - 2*MARGIN - 8*mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='right') template = PageTemplate(id='twocol', frames=[f_left, f_right], onPage=self.add_page_deco) self.addPageTemplates([template]) def add_page_deco(self, canvas, doc): canvas.saveState() # Header bar canvas.setFillColor(C_NAVY) canvas.rect(MARGIN, H - 8*mm, W - 2*MARGIN, 6*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica-Bold', 7) canvas.drawString(MARGIN + 2*mm, H - 5*mm, 'MICROBIOLOGY QUICK REVISION | Apurva Shastri Professional Exam') canvas.setFont('Helvetica', 6) canvas.drawRightString(W - MARGIN, H - 5*mm, f'Page {doc.page}') # Footer bar canvas.setFillColor(C_TEAL) canvas.rect(MARGIN, MARGIN, W - 2*MARGIN, 4*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica', 5.5) canvas.drawCentredString(W/2, MARGIN + 1*mm, 'General Microbiology | Bacteriology | Applied Microbiology | Clinical Microbiology | Immunology') # Column divider mid_x = MARGIN + COL_W + COL_GAP/2 canvas.setStrokeColor(colors.HexColor('#b0bec5')) canvas.setLineWidth(0.5) canvas.line(mid_x, MARGIN + 5*mm, mid_x, H - 8.5*mm) canvas.restoreState() from reportlab.platypus import FrameBreak, NextPageTemplate # Title page elements (will go into left frame, then flow into right) title_fl = [ Spacer(1, 1*mm), Paragraph('MICROBIOLOGY – QUICK REVISION', ST['title']), Paragraph('Apurva Shastri | Professional Exam | All Questions Answered', ST['sub']), HRFlowable(width=COL_W, thickness=1.5, color=C_NAVY, spaceAfter=3), ] + all_fl out = '/home/daytona/workspace/Microbiology_5Page_Revision.pdf' doc = TwoColDoc(out, pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=9*mm, bottomMargin=6*mm) doc.build(title_fl) from pypdf import PdfReader r = PdfReader(out) print(f'Pages: {len(r.pages)}') import os print(f'Size: {os.path.getsize(out)/1024:.1f} KB') print('Output:', out) PYEOF python3 /home/daytona/workspace/build_ultra_compact.py
cat << 'PYEOF' > /home/daytona/workspace/build_3col.py from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import (Paragraph, Spacer, Table, TableStyle, HRFlowable, BaseDocTemplate, PageTemplate, FrameBreak) from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_CENTER from reportlab.platypus.frames import Frame import re, os W, H = A4 MARGIN = 7*mm COL_GAP = 3*mm N_COLS = 3 COL_W = (W - 2*MARGIN - (N_COLS-1)*COL_GAP) / N_COLS C_NAVY = colors.HexColor('#0d1b6e') C_TEAL = colors.HexColor('#005f5f') C_ORANGE = colors.HexColor('#bf360c') C_PURPLE = colors.HexColor('#4a148c') C_RED = colors.HexColor('#b71c1c') C_LGREY = colors.HexColor('#f5f5f5') C_LBLUE = colors.HexColor('#e8f4fd') SEC_COLS = [colors.HexColor('#0d1b6e'), colors.HexColor('#005f5f'), colors.HexColor('#1b5e20'), colors.HexColor('#4a148c'), colors.HexColor('#bf360c'), colors.HexColor('#006064'), colors.HexColor('#311b92'), colors.HexColor('#880e4f')] sec_i = [0] FS = 5.2 LD = 6.5 def S(name, **kw): d = dict(fontName='Helvetica', fontSize=FS, leading=LD, spaceAfter=0.3, spaceBefore=0) d.update(kw) return ParagraphStyle(name, **d) ST = { 'title': S('t', fontName='Helvetica-Bold', fontSize=8.5, leading=10, textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=1.5), 'sub': S('s', fontSize=6, leading=7.5, alignment=TA_CENTER, textColor=C_TEAL, spaceAfter=2), 'h2': S('h2', fontName='Helvetica-Bold', fontSize=6, leading=7.5, textColor=colors.white, backColor=C_TEAL, borderPadding=(1,3,1,3), spaceAfter=0.5, spaceBefore=2), 'h3': S('h3', fontName='Helvetica-Bold', fontSize=5.2, leading=6.5, textColor=C_NAVY, spaceAfter=0.3, spaceBefore=1), 'body': S('body'), 'bullet':S('bullet', leftIndent=6, firstLineIndent=0, spaceAfter=0.2), } def clean(t): t = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', t) return t def parse(raw): items = [] for line in raw.splitlines(): s = line.strip() if not s: continue if re.match(r'^#{1,2} ', s) and not s.startswith('###'): # treat both H1 and H2 as section headers txt = re.sub(r'^#+\s*', '', s) items.append(('h1', txt)) elif s.startswith('### '): items.append(('h2', s[4:].strip())) elif re.match(r'^\|.+\|', s): cells = [c.strip() for c in s.split('|') if c.strip()] if cells and not re.match(r'^[-:]+$', cells[0]): items.append(('tr', cells)) elif re.match(r'^[•\-\*] ', s) or re.match(r'^\d+\. ', s): text = re.sub(r'^[•\-\*\d]+\.?\s*', '', s) items.append(('bullet', '• ' + clean(text))) elif s == '---': pass # skip else: items.append(('body', clean(s))) return items def flowable(kind, text): if kind == 'h1': c = sec_i[0] % len(SEC_COLS); sec_i[0] += 1 st = ParagraphStyle('h1x', fontName='Helvetica-Bold', fontSize=6.2, leading=7.8, textColor=colors.white, backColor=SEC_COLS[c], borderPadding=(1.5,4,1.5,4), spaceAfter=0.5, spaceBefore=3) return Paragraph(f' {text}', st) elif kind == 'h2': return Paragraph(f' {text}', ST['h2']) elif kind == 'h3': return Paragraph(f'<font color="#bf360c">▌</font><b>{text}</b>', ST['h3']) elif kind == 'bullet': return Paragraph(text, ST['bullet']) else: return Paragraph(text, ST['body']) def build_flowables(items): fls = [] i = 0 while i < len(items): kind, text = items[i] if kind == 'tr': rows = [] while i < len(items) and items[i][0] == 'tr': rows.append(items[i][1]); i += 1 if not rows: continue ncols = max(len(r) for r in rows) avail = COL_W - 4 col_w = [avail / ncols] * ncols th_st = ParagraphStyle('th', fontName='Helvetica-Bold', fontSize=4.5, leading=5.5, textColor=colors.white) td_st = ParagraphStyle('td', fontName='Helvetica', fontSize=4.5, leading=5.5) tdata = [] for ri, row in enumerate(rows): while len(row) < ncols: row.append('') row = row[:ncols] if ri == 0: tdata.append([Paragraph(c, th_st) for c in row]) else: tdata.append([Paragraph(c, td_st) for c in row]) t = Table(tdata, colWidths=col_w, repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(-1,0), C_TEAL), ('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white, C_LGREY]), ('GRID',(0,0),(-1,-1),0.2, colors.HexColor('#b0bec5')), ('LEFTPADDING',(0,0),(-1,-1),1.5), ('RIGHTPADDING',(0,0),(-1,-1),1.5), ('TOPPADDING',(0,0),(-1,-1),0.8), ('BOTTOMPADDING',(0,0),(-1,-1),0.8), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) fls.append(t) fls.append(Spacer(1, 1)) else: fls.append(flowable(kind, text)) i += 1 return fls class ThreeColDoc(BaseDocTemplate): def __init__(self, fn, **kw): super().__init__(fn, **kw) frames = [] for col in range(N_COLS): x = MARGIN + col * (COL_W + COL_GAP) f = Frame(x, MARGIN + 5*mm, COL_W, H - 2*MARGIN - 13*mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id=f'col{col}') frames.append(f) tmpl = PageTemplate(id='3col', frames=frames, onPage=self.deco) self.addPageTemplates([tmpl]) def deco(self, canvas, doc): canvas.saveState() # Header canvas.setFillColor(C_NAVY) canvas.rect(MARGIN, H - 8.5*mm, W - 2*MARGIN, 7*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica-Bold', 6.5) canvas.drawString(MARGIN+2*mm, H - 5.2*mm, 'MICROBIOLOGY QUICK REVISION | Apurva Shastri Professional Exam') canvas.setFont('Helvetica', 5.5) canvas.drawRightString(W - MARGIN, H - 5.2*mm, f'Page {doc.page}') # Colored accent stripe under header canvas.setFillColor(C_TEAL) canvas.rect(MARGIN, H - 9.5*mm, W - 2*MARGIN, 1*mm, fill=1, stroke=0) # Footer canvas.setFillColor(colors.HexColor('#37474f')) canvas.rect(MARGIN, MARGIN, W - 2*MARGIN, 4*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica', 4.8) canvas.drawCentredString(W/2, MARGIN + 1.2*mm, 'General Microbiology | Bacteriology | Applied Micro | Clinical Micro | Immunology') # Column dividers for col in range(1, N_COLS): x = MARGIN + col * (COL_W + COL_GAP) - COL_GAP/2 canvas.setStrokeColor(colors.HexColor('#cfd8dc')) canvas.setLineWidth(0.5) canvas.line(x, MARGIN+5*mm, x, H - 10*mm) canvas.restoreState() with open('/home/daytona/workspace/doc_raw.txt') as f: raw = f.read() items = parse(raw) fls = build_flowables(items) header = [ Spacer(1, 0.5*mm), Paragraph('MICROBIOLOGY – QUICK REVISION', ST['title']), Paragraph('Apurva Shastri | Professional Exam | Complete Q&A', ST['sub']), HRFlowable(width=COL_W, thickness=1.2, color=C_NAVY, spaceAfter=2), ] out = '/home/daytona/workspace/Microbiology_6Page_Revision.pdf' doc = ThreeColDoc(out, pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=10*mm, bottomMargin=6*mm) doc.build(header + fls) from pypdf import PdfReader r = PdfReader(out) print(f'Pages: {len(r.pages)}') print(f'Size: {os.path.getsize(out)/1024:.1f} KB') print('Done:', out) PYEOF python3 /home/daytona/workspace/build_3col.py
sed -i 's/FS = 5.2/FS = 5.0/' /home/daytona/workspace/build_3col.py sed -i 's/LD = 6.5/LD = 6.2/' /home/daytona/workspace/build_3col.py sed -i "s/spaceAfter=0.3, spaceBefore=0/spaceAfter=0.2, spaceBefore=0/" /home/daytona/workspace/build_3col.py sed -i "s/'spaceAfter=0.5, spaceBefore=3/'spaceAfter=0.3, spaceBefore=2/" /home/daytona/workspace/build_3col.py # Also reduce spaceBefore on h1 sed -i 's/spaceBefore=3/spaceBefore=2/g' /home/daytona/workspace/build_3col.py sed -i 's/spaceBefore=2/spaceBefore=1.5/g' /home/daytona/workspace/build_3col.py sed -i "s/out = '\/home\/daytona\/workspace\/Microbiology_6Page_Revision.pdf'/out = '\/home\/daytona\/workspace\/Microbiology_6Page_Revision.pdf'/" /home/daytona/workspace/build_3col.py python3 /home/daytona/workspace/build_3col.py
cat << 'PYEOF' > /home/daytona/workspace/build_final.py from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import (Paragraph, Spacer, Table, TableStyle, HRFlowable, BaseDocTemplate, PageTemplate) from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_CENTER from reportlab.platypus.frames import Frame import re, os W, H = A4 MARGIN = 6*mm COL_GAP = 2.5*mm N_COLS = 3 COL_W = (W - 2*MARGIN - (N_COLS-1)*COL_GAP) / N_COLS C_NAVY = colors.HexColor('#0d1b6e') C_TEAL = colors.HexColor('#005f5f') C_LGREY = colors.HexColor('#f5f5f5') SEC_COLS = [colors.HexColor('#0d1b6e'), colors.HexColor('#005f5f'), colors.HexColor('#1b5e20'), colors.HexColor('#4a148c'), colors.HexColor('#bf360c'), colors.HexColor('#006064'), colors.HexColor('#311b92'), colors.HexColor('#880e4f')] sec_i = [0] FS = 4.9; LD = 6.1 def S(name, **kw): d = dict(fontName='Helvetica', fontSize=FS, leading=LD, spaceAfter=0.2, spaceBefore=0) d.update(kw); return ParagraphStyle(name, **d) ST = { 'title': S('t', fontName='Helvetica-Bold', fontSize=8, leading=10, textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=1), 'sub': S('s', fontSize=5.8, leading=7, alignment=TA_CENTER, textColor=C_TEAL, spaceAfter=1.5), 'h2': S('h2', fontName='Helvetica-Bold', fontSize=5.8, leading=7.2, textColor=colors.white, backColor=C_TEAL, borderPadding=(1,3,1,3), spaceAfter=0.4, spaceBefore=1.5), 'h3': S('h3', fontName='Helvetica-Bold', fontSize=4.9, leading=6.2, textColor=C_NAVY, spaceAfter=0.2, spaceBefore=0.8), 'body': S('body'), 'bul': S('bul', leftIndent=5, firstLineIndent=0, spaceAfter=0.15), } def clean(t): return re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', t) def parse(raw): items = [] for line in raw.splitlines(): s = line.strip() if not s: continue if re.match(r'^#{1,2}(?!#) ', s): items.append(('h1', re.sub(r'^#+\s*','',s))) elif s.startswith('### '): items.append(('h2', s[4:].strip())) elif re.match(r'^\|.+\|', s): cells = [c.strip() for c in s.split('|') if c.strip()] if cells and not re.match(r'^[-:]+$', cells[0]): items.append(('tr', cells)) elif re.match(r'^[•\-\*] ', s) or re.match(r'^\d+\. ', s): items.append(('bul', '• ' + clean(re.sub(r'^[•\-\*\d]+\.?\s*','',s)))) elif s == '---': pass else: items.append(('body', clean(s))) return items def to_fl(kind, text): if kind == 'h1': c = sec_i[0] % len(SEC_COLS); sec_i[0] += 1 st = ParagraphStyle('h1x', fontName='Helvetica-Bold', fontSize=5.8, leading=7.2, textColor=colors.white, backColor=SEC_COLS[c], borderPadding=(1.2,4,1.2,4), spaceAfter=0.4, spaceBefore=2) return Paragraph(f' {text}', st) elif kind == 'h2': return Paragraph(f' {text}', ST['h2']) elif kind == 'h3': return Paragraph(f'<font color="#bf360c">▌</font><b>{text}</b>', ST['h3']) elif kind == 'bul': return Paragraph(text, ST['bul']) else: return Paragraph(text, ST['body']) def build(items): fls = []; i = 0 while i < len(items): kind, text = items[i] if kind == 'tr': rows = [] while i < len(items) and items[i][0] == 'tr': rows.append(items[i][1]); i += 1 if not rows: continue ncols = max(len(r) for r in rows) cw = [(COL_W-4)/ncols]*ncols th = ParagraphStyle('th', fontName='Helvetica-Bold', fontSize=4.2, leading=5.2, textColor=colors.white) td = ParagraphStyle('td', fontName='Helvetica', fontSize=4.2, leading=5.2) tdata = [] for ri, row in enumerate(rows): while len(row)<ncols: row.append('') row=row[:ncols] tdata.append([Paragraph(c, th if ri==0 else td) for c in row]) t = Table(tdata, colWidths=cw, repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(-1,0),C_TEAL), ('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white,C_LGREY]), ('GRID',(0,0),(-1,-1),0.2,colors.HexColor('#b0bec5')), ('LEFTPADDING',(0,0),(-1,-1),1.5), ('RIGHTPADDING',(0,0),(-1,-1),1.5), ('TOPPADDING',(0,0),(-1,-1),0.6), ('BOTTOMPADDING',(0,0),(-1,-1),0.6), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) fls.append(t); fls.append(Spacer(1,0.8)) else: fls.append(to_fl(kind, text)); i += 1 return fls class Doc3Col(BaseDocTemplate): def __init__(self, fn, **kw): super().__init__(fn, **kw) frames = [] for col in range(N_COLS): x = MARGIN + col*(COL_W+COL_GAP) frames.append(Frame(x, MARGIN+5*mm, COL_W, H-2*MARGIN-14*mm, leftPadding=0,rightPadding=0,topPadding=0,bottomPadding=0, id=f'c{col}')) self.addPageTemplates([PageTemplate(id='3c', frames=frames, onPage=self.deco)]) def deco(self, canvas, doc): canvas.saveState() canvas.setFillColor(C_NAVY) canvas.rect(MARGIN, H-8*mm, W-2*MARGIN, 6.5*mm, fill=1, stroke=0) canvas.setFillColor(colors.HexColor('#26c6da')) canvas.rect(MARGIN, H-8.8*mm, W-2*MARGIN, 0.8*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica-Bold', 6.2) canvas.drawString(MARGIN+2*mm, H-5*mm, 'MICROBIOLOGY QUICK REVISION | Apurva Shastri Professional Exam') canvas.setFont('Helvetica', 5.5) canvas.drawRightString(W-MARGIN, H-5*mm, f'Page {doc.page}') # Footer canvas.setFillColor(colors.HexColor('#263238')) canvas.rect(MARGIN, MARGIN, W-2*MARGIN, 4.2*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica', 4.6) canvas.drawCentredString(W/2, MARGIN+1.3*mm, 'General Microbiology | Bacteriology | Applied Micro | Clinical Micro | Immunology') # Col dividers for col in range(1,N_COLS): x = MARGIN+col*(COL_W+COL_GAP)-COL_GAP/2 canvas.setStrokeColor(colors.HexColor('#90a4ae')) canvas.setLineWidth(0.4) canvas.line(x, MARGIN+5*mm, x, H-9*mm) canvas.restoreState() with open('/home/daytona/workspace/doc_raw.txt') as f: raw = f.read() items = parse(raw) fls = build(items) header = [ Spacer(1, 0.5*mm), Paragraph('MICROBIOLOGY – QUICK REVISION', ST['title']), Paragraph('Apurva Shastri | Professional Exam | Complete Q&A Answers', ST['sub']), HRFlowable(width=COL_W, thickness=1, color=C_NAVY, spaceAfter=1.5), ] out = '/home/daytona/workspace/Microbiology_6Page_Revision.pdf' doc = Doc3Col(out, pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=9*mm, bottomMargin=6*mm) doc.build(header + fls) from pypdf import PdfReader r = PdfReader(out) print(f'Pages: {len(r.pages)}') print(f'Size: {os.path.getsize(out)/1024:.1f} KB') print('Done:', out) PYEOF python3 /home/daytona/workspace/build_final.py
Microbiology 6Page Revision
PDF Document · PDF
Make it in 10 page
cat << 'PYEOF' > /home/daytona/workspace/build_10page.py from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import (Paragraph, Spacer, Table, TableStyle, HRFlowable, BaseDocTemplate, PageTemplate) from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_CENTER from reportlab.platypus.frames import Frame import re, os W, H = A4 MARGIN = 8*mm COL_GAP = 4*mm N_COLS = 2 COL_W = (W - 2*MARGIN - (N_COLS-1)*COL_GAP) / N_COLS C_NAVY = colors.HexColor('#0d1b6e') C_TEAL = colors.HexColor('#005f5f') C_ORANGE = colors.HexColor('#bf360c') C_LGREY = colors.HexColor('#f5f5f5') C_LBLUE = colors.HexColor('#e8f4fd') C_LGREEN = colors.HexColor('#e8f5e9') C_LYELL = colors.HexColor('#fffff0') SEC_COLS = [ colors.HexColor('#0d1b6e'), # navy colors.HexColor('#00695c'), # dark teal colors.HexColor('#1b5e20'), # dark green colors.HexColor('#4a148c'), # deep purple colors.HexColor('#bf360c'), # deep orange colors.HexColor('#006064'), # cyan dark colors.HexColor('#311b92'), # indigo colors.HexColor('#880e4f'), # pink dark colors.HexColor('#33691e'), # light green dark colors.HexColor('#01579b'), # light blue dark ] sec_i = [0] FS = 6.2; LD = 7.8 def S(name, **kw): d = dict(fontName='Helvetica', fontSize=FS, leading=LD, spaceAfter=0.5, spaceBefore=0) d.update(kw) return ParagraphStyle(name, **d) ST = { 'title': S('t', fontName='Helvetica-Bold', fontSize=10, leading=13, textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=2), 'sub': S('s', fontSize=7, leading=9, alignment=TA_CENTER, textColor=C_TEAL, spaceAfter=3), 'h2': S('h2', fontName='Helvetica-Bold', fontSize=7, leading=9, textColor=colors.white, backColor=C_TEAL, borderPadding=(2,5,2,5), spaceAfter=1, spaceBefore=3), 'h3': S('h3', fontName='Helvetica-Bold', fontSize=6.5, leading=8, textColor=C_NAVY, spaceAfter=0.5, spaceBefore=2), 'body': S('body'), 'bul': S('bul', leftIndent=8, firstLineIndent=0, spaceAfter=0.4), } def clean(t): return re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', t) def parse(raw): items = [] for line in raw.splitlines(): s = line.strip() if not s: continue if re.match(r'^#{1,2}(?!#) ', s): items.append(('h1', re.sub(r'^#+\s*','',s))) elif s.startswith('### '): items.append(('h2', s[4:].strip())) elif re.match(r'^\|.+\|', s): cells = [c.strip() for c in s.split('|') if c.strip()] if cells and not re.match(r'^[-:]+$', cells[0]): items.append(('tr', cells)) elif re.match(r'^[•\-\*] ', s) or re.match(r'^\d+\. ', s): items.append(('bul', '• ' + clean(re.sub(r'^[•\-\*\d]+\.?\s*','',s)))) elif s == '---': pass else: items.append(('body', clean(s))) return items def to_fl(kind, text): if kind == 'h1': c = sec_i[0] % len(SEC_COLS); sec_i[0] += 1 bg = SEC_COLS[c] # lighter tint for left accent bar st = ParagraphStyle('h1x', fontName='Helvetica-Bold', fontSize=7.2, leading=9, textColor=colors.white, backColor=bg, borderPadding=(2,5,2,5), spaceAfter=1, spaceBefore=4) return Paragraph(f' {text}', st) elif kind == 'h2': return Paragraph(f' {text}', ST['h2']) elif kind == 'h3': return Paragraph( f'<font color="#bf360c">▌</font> <b>{text}</b>', ST['h3']) elif kind == 'bul': return Paragraph(text, ST['bul']) else: return Paragraph(text, ST['body']) def build(items): fls = []; i = 0 while i < len(items): kind, text = items[i] if kind == 'tr': rows = [] while i < len(items) and items[i][0] == 'tr': rows.append(items[i][1]); i += 1 if not rows: continue ncols = max(len(r) for r in rows) cw = [(COL_W - 6) / ncols] * ncols th = ParagraphStyle('th', fontName='Helvetica-Bold', fontSize=5.2, leading=6.5, textColor=colors.white) td = ParagraphStyle('td', fontName='Helvetica', fontSize=5.2, leading=6.5) tdata = [] for ri, row in enumerate(rows): while len(row) < ncols: row.append('') row = row[:ncols] tdata.append([Paragraph(c, th if ri==0 else td) for c in row]) t = Table(tdata, colWidths=cw, repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(-1,0), C_TEAL), ('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white, C_LGREY]), ('GRID',(0,0),(-1,-1),0.3, colors.HexColor('#b0bec5')), ('LEFTPADDING',(0,0),(-1,-1), 2), ('RIGHTPADDING',(0,0),(-1,-1), 2), ('TOPPADDING',(0,0),(-1,-1), 1), ('BOTTOMPADDING',(0,0),(-1,-1), 1), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) fls.append(t) fls.append(Spacer(1, 2)) else: fls.append(to_fl(kind, text)); i += 1 return fls class Doc2Col(BaseDocTemplate): def __init__(self, fn, **kw): super().__init__(fn, **kw) frames = [] for col in range(N_COLS): x = MARGIN + col * (COL_W + COL_GAP) frames.append(Frame(x, MARGIN+5*mm, COL_W, H-2*MARGIN-14*mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id=f'c{col}')) self.addPageTemplates([PageTemplate(id='2c', frames=frames, onPage=self.deco)]) def deco(self, canvas, doc): canvas.saveState() # Header gradient-like bar canvas.setFillColor(C_NAVY) canvas.rect(MARGIN, H-9*mm, W-2*MARGIN, 7.5*mm, fill=1, stroke=0) # Accent stripe canvas.setFillColor(colors.HexColor('#26c6da')) canvas.rect(MARGIN, H-9.8*mm, W-2*MARGIN, 0.9*mm, fill=1, stroke=0) # Header text canvas.setFillColor(colors.white) canvas.setFont('Helvetica-Bold', 7) canvas.drawString(MARGIN+3*mm, H-5.5*mm, 'MICROBIOLOGY QUICK REVISION | Apurva Shastri Professional Exam') canvas.setFont('Helvetica', 6) canvas.drawRightString(W-MARGIN, H-5.5*mm, f'Page {doc.page}') # Sub-header in lighter color canvas.setFillColor(colors.HexColor('#b2ebf2')) canvas.setFont('Helvetica', 5.5) canvas.drawString(MARGIN+3*mm, H-8*mm, 'General Microbiology · Bacteriology · Applied Micro · Clinical Micro · Immunology') # Footer canvas.setFillColor(colors.HexColor('#1a237e')) canvas.rect(MARGIN, MARGIN, W-2*MARGIN, 4.5*mm, fill=1, stroke=0) canvas.setFillColor(colors.HexColor('#80deea')) canvas.rect(MARGIN, MARGIN+4.5*mm, W-2*MARGIN, 0.6*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica', 5.2) canvas.drawCentredString(W/2, MARGIN+1.5*mm, 'All rights reserved | For exam revision only | Apurva Shastri Microbiology Paper I') # Column divider mid_x = MARGIN + COL_W + COL_GAP/2 canvas.setStrokeColor(colors.HexColor('#90a4ae')) canvas.setLineWidth(0.5) canvas.setDash(2, 2) canvas.line(mid_x, MARGIN+5.5*mm, mid_x, H-10*mm) canvas.restoreState() with open('/home/daytona/workspace/doc_raw.txt') as f: raw = f.read() items = parse(raw) fls = build(items) header = [ Spacer(1, 1*mm), Paragraph('MICROBIOLOGY – QUICK REVISION', ST['title']), Paragraph('Apurva Shastri | Professional Exam | Complete Q&A Reference', ST['sub']), HRFlowable(width=COL_W, thickness=1.5, color=C_NAVY, spaceAfter=3), ] out = '/home/daytona/workspace/Microbiology_10Page_Revision.pdf' doc = Doc2Col(out, pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=10*mm, bottomMargin=7*mm) doc.build(header + fls) from pypdf import PdfReader r = PdfReader(out) print(f'Pages: {len(r.pages)}') print(f'Size: {os.path.getsize(out)/1024:.1f} KB') print('Done:', out) PYEOF python3 /home/daytona/workspace/build_10page.py
python3 -c " # Read the script, tighten spacing slightly with open('/home/daytona/workspace/build_10page.py') as f: code = f.read() # Reduce spaceBefore on h1 and h2, reduce spaceAfter on bullet code = code.replace('spaceAfter=1, spaceBefore=4', 'spaceAfter=0.8, spaceBefore=3') code = code.replace('spaceAfter=1, spaceBefore=3', 'spaceAfter=0.8, spaceBefore=2') code = code.replace('spaceAfter=0.5, spaceBefore=2', 'spaceAfter=0.4, spaceBefore=1.5') code = code.replace(\"spaceAfter=0.4),\", \"spaceAfter=0.3),\") # Slightly reduce FS and LD code = code.replace('FS = 6.2; LD = 7.8', 'FS = 6.0; LD = 7.5') # Output to new file code = code.replace( \"out = '/home/daytona/workspace/Microbiology_10Page_Revision.pdf'\", \"out = '/home/daytona/workspace/Microbiology_10Page_Revision.pdf'\" ) with open('/home/daytona/workspace/build_10page2.py', 'w') as f: f.write(code) print('written') " python3 /home/daytona/workspace/build_10page2.py
Microbiology 10Page Revision
PDF Document · PDF
Consize in 10-12 pages
python3 -c " from pypdf import PdfReader path = '/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/DOC-20260713-WA0000. (1).pdf' reader = PdfReader(path) print(f'Pages: {len(reader.pages)}') full_text = '' for page in reader.pages: full_text += page.extract_text() + '\n' print(f'Total chars: {len(full_text)}') with open('/home/daytona/workspace/new_doc_raw.txt', 'w') as f: f.write(full_text) print(full_text[:500]) "
python3 -c " with open('/home/daytona/workspace/build_10page2.py') as f: code = f.read() # Point to new source file code = code.replace( \"open('/home/daytona/workspace/doc_raw.txt')\", \"open('/home/daytona/workspace/new_doc_raw.txt')\" ) # New output name code = code.replace( \"out = '/home/daytona/workspace/Microbiology_10Page_Revision.pdf'\", \"out = '/home/daytona/workspace/Microbiology_Concise_10Pages.pdf'\" ) # Bump font slightly for better readability in 10-12 page target code = code.replace('FS = 6.0; LD = 7.5', 'FS = 6.5; LD = 8.0') with open('/home/daytona/workspace/build_concise.py', 'w') as f: f.write(code) print('written') " python3 /home/daytona/workspace/build_concise.py
Microbiology Concise 10Pages
PDF Document · PDF
Answer it
python3 -c " from pypdf import PdfReader reader = PdfReader('/home/daytona/workspace/attachments/592909a5-4bee-46a0-8f89-a4b217c948b5/Microbiology_Paper_2.pdf') print(f'Pages: {len(reader.pages)}') for i, page in enumerate(reader.pages): print(f'--- PAGE {i+1} ---') print(page.extract_text()) "
| Class | Heavy chain | Subclasses | Key feature |
|---|---|---|---|
| IgG | γ | IgG1, IgG2, IgG3, IgG4 | Most abundant; crosses placenta |
| IgA | α | IgG1, IgA2 | Mucosal immunity; SIgA |
| IgM | μ | None | Pentamer; 1st response |
| IgD | δ | None | B-cell surface receptor |
| IgE | ε | None | Allergy; antiparasitic |
| Feature | Agglutination | Precipitation |
|---|---|---|
| Antigen | Particulate (cells, bacteria, inert particles coated with antigen) | Soluble antigen |
| Result | Visible clumping/agglutination | Visible precipitate (line, ring, turbidity) |
| Mechanism | Cross-linking of particulate antigens by antibody | Lattice formation between soluble antigen and antibody at equivalence zone |
| Sensitivity | More sensitive | Less sensitive |
| Examples | Widal test (S. typhi O/H agglutinins), ABO blood grouping, TPHA | Ouchterlony double diffusion, Elek's test, Immunoelectrophoresis |
| Type | Name | Mechanism | Antibody/Cell | Time | Examples |
|---|---|---|---|---|---|
| I | Immediate/Anaphylactic | IgE-mediated mast cell degranulation | IgE | Minutes | Anaphylaxis, asthma, urticaria, hay fever |
| II | Cytotoxic/Antibody-mediated | IgG/IgM + complement; ADCC against cell-surface antigens | IgG, IgM | Hours | Hemolytic anemia, HDN, Goodpasture's, myasthenia gravis |
| III | Immune Complex-mediated | IgG immune complexes deposited in tissues → complement activation → inflammation | IgG (soluble immune complexes) | 4-8 hrs | SLE, post-streptococcal GN, serum sickness, Farmer's lung (Arthus reaction) |
| IV | Delayed-type/Cell-mediated | T cell (CD4+ Th1, CD8+ CTL) mediated | T cells (no antibody) | 48-72 hrs | TB, contact dermatitis, transplant rejection, Mantoux test |
| Route | Cavity/Membrane | Example viruses |
|---|---|---|
| Chorioallantoic membrane (CAM) | Surface of CAM | HSV (pocks), Vaccinia, Poxviruses |
| Allantoic cavity | Allantoic fluid | Influenza, Mumps, Newcastle disease |
| Amniotic cavity | Amniotic fluid | Influenza (primary isolation), Mumps |
| Yolk sac | Yolk sac | Chlamydia, Rickettsia, Arboviruses, HSV |
| Intravenous (vitelline vein) | Blood | Yellow fever virus |
| Marker | Significance | When appears |
|---|---|---|
| HBsAg | Surface antigen; first marker; active infection | 4-12 weeks |
| Anti-HBc IgM | Acute/recent infection | 6-14 weeks |
| HBeAg | High infectivity, active replication | With HBsAg |
| HBV DNA | Most sensitive marker of replication | Early |
| Anti-HBe | Seroconversion; lower infectivity | After HBeAg |
| Anti-HBs | Recovery; immunity (vaccination) | >20 weeks |
| Anti-HBc IgG | Past exposure (lifelong) | Persists |
| Feature | Salk's Vaccine (IPV - Inactivated Polio Vaccine) | Sabin's Vaccine (OPV - Oral Polio Vaccine) |
|---|---|---|
| Type | Killed/inactivated (formaldehyde) | Live attenuated |
| Route | IM injection | Oral (2 drops) |
| Types covered | All 3 serotypes | All 3 serotypes (trivalent/bivalent) |
| Immunity induced | Humoral (IgG) - good; NO mucosal IgA | Both humoral AND mucosal (sIgA in gut) |
| Herd immunity | Poor (no gut immunity; virus can still replicate in gut) | Excellent - immunized person spreads virus to contacts (passive immunization of community) |
| Stability | Stable; no cold chain issues | Requires cold chain (heat labile) |
| VAPP risk | None | Vaccine-Associated Paralytic Poliomyelitis (VAPP) - 1 per 2.4 million doses |
| Safety | Safe in immunocompromised | Contraindicated in immunocompromised |
| Cost | More expensive | Cheaper; easier to administer |
| Use today | Used in polio-free countries (UK, USA) | Used in endemic areas (India now switched to bOPV + IPV) |
| Subfamily | Characteristics | Members | One infection |
|---|---|---|---|
| Alphaherpesvirinae | Fast growth; short cycle; latency in neurons | HSV-1, HSV-2, VZV | HSV-1 → oral herpes (cold sores); VZV → chickenpox |
| Betaherpesvirinae | Slow growth; large cells (cytomegaly); latency in glands, monocytes | CMV, HHV-6, HHV-7 | CMV → congenital CMV, retinitis in AIDS |
| Gammaherpesvirinae | Lymphotropic; latency in lymphocytes; oncogenic | EBV (HHV-4), KSHV/HHV-8 | EBV → Infectious mononucleosis; KSHV → Kaposi's sarcoma |
| Strategy | When | Method |
|---|---|---|
| Strategy I | Blood safety | Single ELISA; if +ve, blood discarded |
| Strategy II | Surveillance (low prevalence) | 2 ELISAs; if discordant, 3rd test |
| Strategy III | Diagnosis in symptomatic individuals | 3 sequential ELISAs with different antigens; 3 positives = HIV positive |
| Virus | Family | Genome | Transmission | Chronicity | Vaccine |
|---|---|---|---|---|---|
| HAV | Picornaviridae | +ssRNA | Feco-oral | No | Yes |
| HBV | Hepadnaviridae | Partially dsDNA (circular) | Parenteral, sexual, vertical | Yes (5-10%) | Yes |
| HCV | Flaviviridae | +ssRNA | Parenteral | Yes (70-80%) | No |
| HDV | Deltaviridae | -ssRNA (defective; needs HBV) | Parenteral (co/super-infection) | Yes | Via HBV vaccine |
| HEV | Hepeviridae | +ssRNA | Feco-oral | No (except immunocompromised) | Yes (China only) |
| Category | Description | Examples |
|---|---|---|
| Yeasts | Unicellular; reproduce by budding; circular/oval | Candida, Cryptococcus, Malassezia |
| Moulds (Filamentous fungi) | Multicellular; grow as hyphae/mycelium | Aspergillus, Rhizopus, Trichophyton, Sporothrix |
| Dimorphic fungi | Exist as yeast at 37°C (tissue) and mould at 25°C (environment) | Histoplasma, Blastomyces, Coccidioides, Sporothrix, Paracoccidioides |
| Yeasts with pseudohyphae | Elongated buds that fail to separate | Candida species |
| Category | Description | Organisms |
|---|---|---|
| Superficial mycoses | Skin surface, hair shaft | Malassezia furfur (pityriasis versicolor), Trichosporon |
| Cutaneous mycoses | Skin, hair, nails (keratinized layers) | Dermatophytes (Trichophyton, Microsporum, Epidermophyton) |
| Subcutaneous mycoses | Dermis and subcutis | Sporothrix schenckii, Madurella, Fonsecaea |
| Systemic mycoses | Lungs and disseminate | Histoplasma, Coccidioides, Blastomyces, Paracoccidioides |
| Opportunistic mycoses | In immunocompromised | Candida, Aspergillus, Cryptococcus, Mucor, PCP |
| Smear | Advantage | Stain |
|---|---|---|
| Thick film | Concentrates RBCs; better sensitivity | Giemsa (or Leishman) |
| Thin film | Species identification by RBC morphology; morphology best | Giemsa + fixed with methanol |
| Feature | P. vivax | P. falciparum | P. malariae | P. ovale |
|---|---|---|---|---|
| RBC size | Enlarged | Normal or small | Normal | Slightly enlarged, oval |
| Schüffner's dots | Present | Absent (Maurer's clefts) | Absent | Present (James' dots) |
| Trophozoite | Amoeboid | Ring forms only; accole forms; multiple rings/RBC | Band/ribbon form | Compact |
| Gametocyte | Round | Banana/crescent-shaped (diagnostic) | Round | Round |
| Feature | T. saginata (Beef tapeworm) | T. solium (Pork tapeworm) |
|---|---|---|
| Intermediate host | Cattle (beef) | Pig (pork); ALSO humans (cysticercosis) |
| Scolex | No hooks, no rostellum ("unarmed") | Has hooks (22-32) on rostellum ("armed") |
| Proglottids | Uterine branches: 15-30 lateral branches | Uterine branches: 7-12 lateral branches |
| Danger to humans | Intestinal tapeworm only (cysticercosis does NOT occur) | Both intestinal tapeworm AND cysticercosis (neurocysticercosis - dangerous) |
| Size | Longer (up to 10 m) | Shorter (2-7 m) |
| Cysticercus | Not in humans | Can form in human brain, muscle, eye (cysticercosis) |
| Cestode | Intermediate host | Human infection |
|---|---|---|
| Taenia saginata | Cattle | Intestinal tapeworm |
| Taenia solium | Pig; Humans | Intestinal tapeworm + Cysticercosis |
| Echinococcus granulosus | Sheep/cattle/humans | Hydatid cyst |
| Echinococcus multilocularis | Rodents | Alveolar echinococcosis |
| Diphyllobothrium latum | Copepod → fish | B12 deficiency megaloblastic anemia |
| Hymenolepis nana | Humans (no intermediate host) | Dwarf tapeworm intestinal infection |
| Dipylidium caninum | Flea (dog flea) | Intestinal (children) |
| Group | Organisms |
|---|---|
| Intestinal nematodes | Ascaris, Enterobius, Trichuris, Hookworms, Strongyloides |
| Tissue/blood nematodes (Filariae) | Wuchereria bancrofti, Brugia malayi, Loa loa, Onchocerca volvulus, Dracunculus medinensis |
| Tissue nematodes | Toxocara canis/cati (visceral larva migrans), Trichinella spiralis |
Create a compressed 10-12 page PDF revision guide of Paper II answers with color-coded sections
cat << 'PYEOF' > /home/daytona/workspace/build_paper2.py from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import (Paragraph, Spacer, Table, TableStyle, HRFlowable, BaseDocTemplate, PageTemplate) from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_CENTER from reportlab.platypus.frames import Frame import re, os W, H = A4 MARGIN = 8*mm COL_GAP = 4*mm N_COLS = 2 COL_W = (W - 2*MARGIN - (N_COLS-1)*COL_GAP) / N_COLS # ── Section colour palette (one per major subject) ─────────────────────────── # Immunology=Blue, Virology=Purple, Mycology=Green, Parasitology=Orange SUBJECT_COLORS = { 'IMMUNOLOGY': colors.HexColor('#0d1b6e'), 'INFECTION': colors.HexColor('#1565c0'), 'IMMUNITY': colors.HexColor('#1565c0'), 'ANTIBODY': colors.HexColor('#0277bd'), 'ANTIGEN': colors.HexColor('#006064'), 'COMPLEMENT': colors.HexColor('#00695c'), 'IMMUNE': colors.HexColor('#2e7d32'), 'HYPERSENSITIVITY': colors.HexColor('#4527a0'), 'AUTOIMMUN': colors.HexColor('#6a1b9a'), 'VIROLOGY': colors.HexColor('#4a148c'), 'GENERAL PROP': colors.HexColor('#6a1b9a'), 'VIRUS-HOST': colors.HexColor('#7b1fa2'), 'VIRUSES': colors.HexColor('#880e4f'), 'MYCOLOGY': colors.HexColor('#1b5e20'), 'SUPERFICIAL': colors.HexColor('#2e7d32'), 'SYSTEMIC': colors.HexColor('#33691e'), 'OPPORTUNISTIC': colors.HexColor('#33691e'), 'PARASITOLOGY': colors.HexColor('#bf360c'), 'FLAGELLATE': colors.HexColor('#e65100'), 'SPOROZOA': colors.HexColor('#bf360c'), 'CESTODE': colors.HexColor('#4e342e'), 'NEMATODE': colors.HexColor('#3e2723'), 'DIAGNOSTIC': colors.HexColor('#37474f'), } def get_sec_color(text): t = text.upper() for k, v in SUBJECT_COLORS.items(): if k in t: return v return colors.HexColor('#37474f') C_LGREY = colors.HexColor('#f5f5f5') C_TEAL = colors.HexColor('#005f5f') C_NAVY = colors.HexColor('#0d1b6e') FS = 6.0; LD = 7.6 def S(name, **kw): d = dict(fontName='Helvetica', fontSize=FS, leading=LD, spaceAfter=0.4, spaceBefore=0) d.update(kw); return ParagraphStyle(name, **d) ST = { 'title': S('t', fontName='Helvetica-Bold', fontSize=10, leading=13, textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=2), 'sub': S('s', fontSize=7, leading=9, alignment=TA_CENTER, textColor=C_TEAL, spaceAfter=3), 'h2': S('h2', fontName='Helvetica-Bold', fontSize=7, leading=9, textColor=colors.white, backColor=C_TEAL, borderPadding=(2,5,2,5), spaceAfter=1, spaceBefore=3), 'h3': S('h3', fontName='Helvetica-Bold', fontSize=6.2, leading=8, textColor=C_NAVY, spaceAfter=0.5, spaceBefore=2), 'body': S('body'), 'bul': S('bul', leftIndent=8, firstLineIndent=0, spaceAfter=0.3), } def clean(t): t = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', t) t = re.sub(r'\*(.+?)\*', r'<i>\1</i>', t) return t # ── The full Paper II content as structured text ───────────────────────────── CONTENT = """ # IMMUNOLOGY ## INFECTION ### Carrier Definitions • Carrier: Harbors pathogen without overt disease; can transmit infection • Contact/Healthy carrier: Harbors pathogen without ever suffering disease (e.g. N. meningitidis, healthy typhoid carriers) • Paradoxical carrier: Acquires infection FROM a carrier (not from a clinical case); carrier infects another • Convalescent carrier: Recovered clinically but still shedding pathogen (e.g. Typhoid Mary – S. typhi in gallbladder; >1 yr = chronic carrier) ## IMMUNITY ### Innate Immunity – Mechanisms • Physical barriers: Intact skin (keratin), mucous membranes, mucociliary escalator, flushing (urine/tears) • Biochemical barriers: Gastric acid (pH 2), lysozyme (NAM-NAG cleavage), lactoferrin (iron deprivation), defensins, complement (alternative pathway), interferons (IFN-α/β – antiviral state), acute phase proteins (CRP, MBL – opsonins), fever • Cellular: Neutrophils (oxidative burst – H₂O₂, MPO, hypochlorite), Macrophages (phagocytosis + cytokines: TNF, IL-1, IL-6, IL-12), NK cells (kill virus-infected cells – "missing self"), Dendritic cells (bridge to adaptive immunity) • PRRs: TLR4 (LPS), TLR9 (CpG DNA), TLR3 (dsRNA), NOD receptors, RIG-I (intracellular) ## ANTIBODY – IMMUNOGLOBULIN ### IgG – Structure and Function • Basic unit: 2 heavy γ-chains + 2 light chains (κ or λ); MW 150 kDa (7S) • Fab fragment (2): VH+VL+CH1+CL → antigen binding site • Fc fragment (1): CH2+CH3 → effector functions; binds FcγR on phagocytes • Papain cleaves → 2 Fab + 1 Fc; Pepsin cleaves below hinge → F(ab')₂ + pFc' • Subclasses: IgG1, IgG2, IgG3 (complement), IgG4 (no complement) • Functions: Most abundant (75-80%); opsonization; complement activation; neutralization; ADCC; placental transfer (via FcRn – only Ig to cross placenta); longest half-life (~23 days); main antibody in secondary response ### IgM – Structure, Properties and Functions • Pentamer: 5 monomers joined by J-chain; MW 900 kDa (19S); 10 antigen-binding sites • Properties: First Ab in primary response (earliest infection marker); largest Ig; confined to intravascular space (doesn't cross placenta); most efficient complement activator (single molecule activates C1q); best agglutinating Ab (high valency); half-life 5 days; surface monomer = BCR • Functions: Primary response; agglutination; complement activation; ABO blood group Abs (anti-A, anti-B) are IgM ### IgA – Structure • Serum IgA: Monomer (160 kDa, 7S) • Secretory IgA (sIgA): Dimer + J-chain + Secretory Component (SC protects from proteolysis) • Found in: Saliva, tears, colostrum, breast milk, respiratory/GI/GU secretions • First line of mucosal defense – prevents pathogen adherence to epithelium ### Immunoglobulin Classes Summary | Class | Chain | Structure | Key Feature | |---|---|---|---| | IgG | γ | Monomer | Most abundant; crosses placenta; secondary response | | IgA | α | Monomer/Dimer | Mucosal immunity (sIgA) | | IgM | μ | Pentamer | First response; best agglutinator; complement | | IgD | δ | Monomer | B-cell surface receptor | | IgE | ε | Monomer | Allergy; antiparasitic; binds mast cells/basophils | ## ANTIGEN-ANTIBODY REACTIONS ### Agglutination vs Precipitation | Feature | Agglutination | Precipitation | |---|---|---| | Antigen | Particulate (cells, bacteria, coated particles) | Soluble | | Result | Visible clumping | Visible precipitate (line/ring/turbidity) | | Sensitivity | More sensitive | Less sensitive | | Mechanism | Cross-linking of particles by Ab | Lattice formation at equivalence | | Examples | Widal test, TPHA, ABO grouping | VDRL, Elek's test, Ouchterlony | ### ELISA – Principle and Applications • Types: Direct (enzyme-Ab on Ag), Indirect (detects patient Ab), Sandwich (most sensitive – antigen detection), Competitive (inversely proportional signal) • Applications: HIV serology, HBsAg, Dengue NS1, blood bank screening, drug monitoring, hormone assays (hCG, TSH), food safety, cytokine quantification ### Widal Test • Tube agglutination detecting O and H agglutinins against S. typhi • Serial dilutions (1:20–1:640+) + Salmonella antigens (TO, TH, AO, AH, BO, BH) → 37°C/24 hrs • Significant: O ≥1:80, H ≥1:160 (endemic); fourfold rise in paired sera = diagnostic • O agglutination = granular (active infection); H agglutination = fluffy (past/vaccination) • Prozone phenomenon: False-negative due to antibody excess → dilute serum to overcome ### Precipitation Reactions • Ring test: Interface precipitin ring • Ouchterlony (double diffusion): Lines of identity/partial identity/non-identity • SRID/Mancini: Ring diameter² ∝ Ag concentration (quantifies Ig) • Immunoelectrophoresis: Separates then precipitates (M-band in myeloma) • CIE: Electrophoresis drives Ag+Ab together rapidly; CSF antigen detection ### Passive Agglutination • Soluble antigens coated on carrier particles → agglutinate with specific Ab • Carriers: RBCs (IHA), Latex beads (LAT), Charcoal (RPR) • Examples: TPHA (syphilis), RA latex (rheumatoid factor), LAT (meningococcal CSF Ag), RPR (syphilis screening) ## COMPLEMENT SYSTEM ### Classical Pathway • Activation: IgG (×2) or IgM (×1) bound to Ag activates C1q → C1r → C1s • C1s cleaves C4 → C4a (anaphylatoxin) + C4b (surface) • C4b+C2 → C1s cleaves C2 → C3 convertase (C4b2a) • C3 convertase cleaves C3 → C3a (anaphylatoxin+chemotaxis) + C3b (opsonin) • C5 convertase (C4b2a3b) → C5a (most potent anaphylatoxin+chemotaxis) + C5b • Terminal: C5b+C6+C7+C8+poly-C9 → MAC (Membrane Attack Complex) → bacterial lysis • Biological effects: Lysis, opsonization (C3b→CR1), anaphylatoxins (C3a/C4a/C5a→mast cell degranulation), chemotaxis (C5a), immune complex solubilization, B-cell activation (C3d→CR2) • Alternative pathway: Activated by LPS, zymosan, cobra venom – no antibody needed (C3bBb, stabilized by properdin) • Lectin pathway: MBL binds mannose on bacteria → MASP1/2 → cleave C4, C2 ## IMMUNE RESPONSE ### Cell-Mediated Immunity – Detection Tests • In vivo: Mantoux/tuberculin test (PPD, 48-72 hrs induration), Lepromin test (Mitsuda), DNCB sensitization, Candida/Mumps recall antigen tests • In vitro: Lymphocyte Transformation Test (³H-thymidine incorporation), LMIT (MIF produced by sensitized T cells inhibits macrophage migration), CTL assay (⁵¹Cr release), Flow cytometry (CD4/CD8 ratio), ELISPOT (IFN-γ secreting cells), IGRA (QuantiFERON-TB Gold) ## HYPERSENSITIVITY ### Gell and Coombs Classification | Type | Name | Mechanism | Ab/Cell | Onset | Examples | |---|---|---|---|---|---| | I | Anaphylactic | IgE→mast cell degranulation | IgE | Minutes | Anaphylaxis, asthma, urticaria, hay fever | | II | Cytotoxic | IgG/IgM+complement vs cell-surface Ag | IgG/IgM | Hours | Hemolytic anemia, HDN, Goodpasture's, myasthenia gravis | | III | Immune complex | Soluble IC deposition+complement | IgG | 4–8 hrs | SLE, PSGN, serum sickness, Farmer's lung | | IV | Delayed (DTH) | T cell (CD4+Th1, CD8+CTL) mediated | T cells | 48–72 hrs | TB skin test, contact dermatitis, transplant rejection | ### Type I Hypersensitivity (IgE-mediated) – Detail • Sensitization: Allergen→Th2→IL-4/IL-5/IL-13→B cells→IgE→IgE binds FcεRI on mast cells/basophils • Elicitation: Re-exposure→cross-link 2 IgE-FcεRI→Ca²⁺ influx→degranulation • Preformed mediators: Histamine (vasodilation, bronchospasm, itch), heparin, tryptase • Newly synthesized: PGD₂, LTC₄/LTD₄/LTE₄ (SRS-A – bronchospasm, 1000× potent), PAF • Clinical: Anaphylaxis, allergic asthma, allergic rhinitis, urticaria, food allergy, atopic dermatitis • Dx: Total IgE elevated; allergen-specific IgE (RAST/ImmunoCAP); skin prick test • Rx: Epinephrine (anaphylaxis); antihistamines; beta-2 agonists; steroids; anti-IgE (Omalizumab) ### Type III Hypersensitivity – Immune Complex • Soluble Ag-Ab complexes in Ag-excess → not cleared → deposit in vessel walls/glomeruli/synovium • Complement→C3a/C5a→mast cell degranulation+neutrophil chemotaxis→lysosomal enzymes→tissue damage • Local (Arthus): Intradermal Ag in immunized → edema, hemorrhage, necrosis (6–8 hrs) • Systemic (Serum sickness): Foreign serum → fever, urticaria, arthralgia, proteinuria (7–10 days) • Diseases: SLE (anti-dsDNA), PSGN, Rheumatoid arthritis, Hypersensitivity pneumonitis ### Type IV Hypersensitivity (DTH) – Delayed • Sensitization: First exposure→APCs→CD4+Th1 cells sensitized and form memory • Elicitation: Re-exposure→Th1→IFN-γ (activates macrophages), TNF-β, IL-2, MIF • Effectors: Activated macrophages→granuloma (TB, leprosy, sarcoidosis) • Examples: Mantoux test (prototype), contact dermatitis (nickel, urushiol), transplant rejection, GVHD ### Anaphylaxis • Acute, severe, potentially fatal systemic Type I reaction • Mediators: Histamine, LTC4/D4, PAF → vasodilation, bronchospasm, urticaria, cardiovascular collapse • Triggers: Penicillin, bee venom, peanuts, shellfish, latex • Treatment: Epinephrine 0.5 mg IM (first line) + antihistamines + steroids + IV fluids + O₂ ## AUTOIMMUNITY ### Four Features of Autoimmune Diseases • Autoantibodies/autoreactive T cells against self-antigens (anti-dsDNA in SLE; anti-AChR in myasthenia gravis) • HLA/MHC association – genetic predisposition (HLA-DR3/DR4 in T1DM; HLA-B27 in AS) • Female predominance (hormonal influence – oestrogen promotes, testosterone suppresses) • Chronicity with remission-relapse pattern ### Mechanisms of Autoimmunity • Release of sequestered Ag: Hidden antigens exposed by infection/trauma → autoimmune response (sympathetic ophthalmia, orchitis) • Molecular mimicry: Microbial Ag similar to self → cross-reactive Abs/T cells (Strep M protein→cardiac myosin→rheumatic fever; Campylobacter→ganglioside→GBS) • Polyclonal B cell activation: EBV, LPS activate B cells non-specifically → autoantibodies • Epitope spreading: Initial response→tissue damage→new self-Ag released→self-perpetuating • Loss of peripheral tolerance: Treg (FoxP3+) failure; defective Fas/FasL apoptosis • Bystander activation: Inflammation near self-tissue activates APCs→present self-Ag • Superantigen stimulation: Non-specific T cell activation → some autoreactive clones activated # VIROLOGY ## GENERAL PROPERTIES OF VIRUS ### Embryonated Hen's Egg – Routes and Uses | Route | Site | Examples | |---|---|---| | Chorioallantoic membrane (CAM) | CAM surface | HSV (pocks), Vaccinia, Poxviruses | | Allantoic cavity | Allantoic fluid | Influenza, Mumps (vaccine production) | | Amniotic cavity | Amniotic fluid | Influenza (primary isolation), Mumps | | Yolk sac | Yolk sac | Chlamydia, Rickettsia, Arboviruses | | Intravenous | Vitelline vein | Yellow fever virus | ### Detecting Viral Growth in Cell Culture • CPE (most common): Rounding, swelling, syncytia, lysis observed by inverted microscope (HSV→rapid CPE; RSV→syncytia; CMV→owl-eye; Adenovirus→grape cluster) • Haemadsorption: RBCs adsorb to virus-infected cells (HA on surface) – Influenza, Parainfluenza, Mumps • Haemagglutination: Virus in supernatant agglutinates RBCs – Influenza, Mumps • Interference: Non-CPE virus blocks challenge CPE virus (Rubella – blocks Echovirus CPE) • Immunofluorescence: Fluorescent Ab detects viral Ag in infected cells – Rabies, RSV, CMV • Metabolic inhibition: pH stays alkaline (no acid from dead cells) – Enteroviruses • Transformation: Oncogenic viruses → foci of piled-up cells ### Stages of Viral Multiplication • Adsorption: Viral protein binds receptor (HIV gp120→CD4+CCR5; Influenza HA→sialic acid; Rabies→AChR) • Penetration: Receptor-mediated endocytosis OR membrane fusion (enveloped viruses) • Uncoating (eclipse phase): Capsid removed; nucleic acid released • Biosynthesis: DNA viruses in nucleus; RNA viruses in cytoplasm; Retroviruses use RT (RNA→DNA→RNA) • Assembly: Components assembled into virions • Release: Lysis (non-enveloped) OR budding (enveloped – HIV, Influenza; cell survives) ## VIRUS-HOST INTERACTIONS ### Negri Bodies • Intracytoplasmic eosinophilic inclusion bodies in neurons infected with Rabies virus • Location: Hippocampal neurons (Ammon's horn), Purkinje cells of cerebellum • Nature: Aggregates of rabies RNP (ribonucleoprotein) in cytoplasm • Appearance: Eosinophilic, round-oval, 2–10 µm, basophilic inner granules • Demonstration: Seller's stain (magenta Negri bodies, blue-grey neurons); Immunofluorescence (most sensitive) • Absent in ~20% of rabies → IF preferred ### Inclusion Bodies | Type | Stain | Virus | |---|---|---| | Negri bodies (cytoplasmic) | Eosinophilic | Rabies | | Guarnieri bodies (cytoplasmic) | Eosinophilic | Vaccinia/Variola | | Henderson-Patterson (cytoplasmic) | Large, basophilic | Molluscum contagiosum | | Cowdry A (intranuclear) | Eosinophilic, halo, marginated chromatin | HSV, VZV, CMV ("owl eye"), YF | | Cowdry B (intranuclear) | Small, multiple, no halo | Poliovirus | | Adenovirus inclusions (intranuclear) | Basophilic, fills nucleus | Adenovirus | ## VIRUSES ### Hepatitis B – Serological Markers and Lab Diagnosis | Marker | Significance | Timing | |---|---|---| | HBsAg | Surface Ag; FIRST marker; active infection | Week 4–12 | | Anti-HBc IgM | Acute/recent infection; + in window period | Week 6–14 | | HBeAg | High infectivity; active replication | With HBsAg | | HBV DNA (PCR) | Most sensitive replication marker | Early | | Anti-HBe | Seroconversion; lower infectivity | After HBeAg | | Anti-HBs | Recovery + immunity; vaccination marker | >Week 20 | | Anti-HBc IgG | Past exposure (lifelong) | Persists | • Window period: HBsAg negative + Anti-HBs negative → ONLY Anti-HBc IgM positive • Tests: ELISA/CLIA for HBsAg; HBV DNA PCR (quantitative viral load); LFTs; liver biopsy ### Hepatitis Viruses – Classification | Virus | Family | Genome | Transmission | Chronic? | Vaccine | |---|---|---|---|---|---| | HAV | Picornaviridae | +ssRNA | Feco-oral | No | Yes | | HBV | Hepadnaviridae | Partial dsDNA (circular) | Parenteral/sexual/vertical | Yes (5–10%) | Yes | | HCV | Flaviviridae | +ssRNA | Parenteral | Yes (70–80%) | No | | HDV | Deltaviridae | -ssRNA (defective; needs HBV) | Parenteral | Yes | Via HBV vaccine | | HEV | Hepeviridae | +ssRNA | Feco-oral | No (except immunocomp.) | Yes (China) | • HBV pathogenesis: Not directly cytopathic; damage is immune-mediated (CD8+ T cells attack infected hepatocytes); cccDNA in nucleus = basis of chronicity; HCC via HBV DNA integration + HBx protein • Prophylaxis: HBV vaccine (recombinant HBsAg; 0,1,6 months; >95% protection); HBIG for post-exposure; India EPI: birth + 6,10,14 weeks (Pentavalent) ### Rabies – Immunoprophylaxis • Non-neural vaccines: HDCV (MRC-5 cells), PCECV (Rabipur), PVRV (Verobrab) • Post-exposure: Wound wash (soap+water 15 min + povidone iodine) → RIG (HRIG 20 IU/kg OR ERIG 40 IU/kg, Day 0 only, into wound) → Vaccine: Essen schedule (Days 0,3,7,14,28 – 5 doses IM deltoid) OR Zagreb 2-1-1 (Days 0×2 sites, 7, 21 – 4 doses) • Pre-exposure (PrEP): Days 0, 7, 21/28 – 3 doses (vets, lab workers, travelers) ### Influenza Virus – Antigenic Variation • Structure: Enveloped -ssRNA, 8 segments; HA (triangular trimer, binds sialic acid, vaccine target) + NA (mushroom tetramer, cleaves sialic acid, target of oseltamivir/zanamivir); M2 (amantadine target); M1 matrix; NP, PB1/PB2/PA polymerase • Antigenic DRIFT: Gradual point mutations in HA/NA genes (error-prone RdRp) → seasonal epidemics → annual vaccine reformulation; all types A and B • Antigenic SHIFT: Reassortment of gene segments between human + animal (avian/swine) influenza in pig ("mixing vessel") → new HA/NA subtype → pandemic; Type A only; no pre-existing immunity • Pandemics: 1918 H1N1 (Spanish flu), 1957 H2N2, 1968 H3N2, 2009 H1N1 (Swine flu) ### Salk (IPV) vs Sabin (OPV) Vaccines | Feature | Salk IPV | Sabin OPV | |---|---|---| | Type | Killed/inactivated | Live attenuated | | Route | IM injection | Oral (2 drops) | | Immunity | Humoral (IgG) only | Humoral + Mucosal (sIgA) | | Herd immunity | Poor | Excellent (spreads to contacts) | | VAPP risk | None | 1 per 2.4 million doses | | Cold chain | Not needed | Required (heat labile) | | Immunocompromised | Safe | Contraindicated | | Use | Polio-free countries | Endemic areas (India: bOPV+IPV) | ### Herpesviridae – Classification | Subfamily | Members | Key Infection | |---|---|---| | Alphaherpesvirinae (fast; neuron latency) | HSV-1, HSV-2, VZV | HSV-1: oral herpes; VZV: chickenpox/shingles | | Betaherpesvirinae (slow; cytomegaly; gland latency) | CMV, HHV-6, HHV-7 | CMV: congenital CMV, retinitis in AIDS | | Gammaherpesvirinae (lymphotropic; oncogenic) | EBV (HHV-4), KSHV (HHV-8) | EBV: IM, Burkitt's; KSHV: Kaposi's sarcoma | ### HIV – Pathogenesis and Diagnosis • Entry: gp120 binds CD4 + CCR5 (macrophage-tropic, early) or CXCR4 (T-tropic, late); gp41 mediates fusion → RT (error-prone) → proviral DNA → integrase → integrated provirus (permanent) • CD4 decline: Progressive loss (<500 symptomatic; <200 AIDS); CD8 cytotoxic response wanes with time • Structure: gp120+gp41 envelope; p24 capsid (conical); p17 matrix; 2×RNA; RT(p66/p51), IN(p32), PR(p11); genes: gag, pol, env + tat, rev, vif, vpr, vpu, nef • Opportunistic infections: PCP (CD4<200; bilateral interstitial pneumonia), Cryptococcal meningitis (CD4<100), CMV retinitis, MAC, Toxoplasma encephalitis, esophageal candidiasis, Kaposi's sarcoma • Lab diagnosis: 4th gen ELISA/CLIA (Ab+p24 Ag); confirmatory Western blot (gp41, gp120, p24 bands) or LIA; CD4 count (flow cytometry); HIV RNA viral load (PCR/NASBA) • Window period: 2–8 weeks; p24 Ag or NAT detects before Abs appear • India HIV testing strategy: Strategy I (blood safety – 1 ELISA); Strategy II (surveillance – 2 tests); Strategy III (diagnosis – 3 sequential ELISAs with different Ag) ### Epstein-Barr Virus (EBV) • Gammaherpesvirinae (HHV-4); tropism: B lymphocytes (via CD21/CR2) + epithelial cells; latency in memory B cells • Diseases: Infectious mononucleosis (fever, exudative pharyngitis, posterior cervical lymphadenopathy, splenomegaly, Downey cells = activated CD8 T cells; Monospot/Paul-Bunnell test for heterophile Abs), Burkitt's lymphoma (t(8;14) c-myc; jaw tumour), Nasopharyngeal carcinoma, Hodgkin's lymphoma, PTLD, hairy oral leukoplakia (HIV) ### Oncogenic Viruses • HPV 16,18 → cervical/oropharyngeal cancer (E6 degrades p53; E7 inactivates Rb) • HBV+HCV → hepatocellular carcinoma • EBV → Burkitt's lymphoma, nasopharyngeal carcinoma, Hodgkin's lymphoma • KSHV/HHV-8 → Kaposi's sarcoma • HTLV-1 → Adult T-cell leukemia/lymphoma # MYCOLOGY ## GENERAL ASPECTS ### Classification of Medically Important Fungi | Morphological Type | Examples | |---|---| | Yeasts (unicellular, budding) | Candida, Cryptococcus, Malassezia | | Moulds/Filamentous (hyphae+mycelium) | Aspergillus, Rhizopus, Trichophyton, Sporothrix | | Dimorphic (yeast@37°C; mould@25°C) | Histoplasma, Blastomyces, Coccidioides, Sporothrix | | Yeast with pseudohyphae | Candida species | | Disease Category | Organisms | |---|---| | Superficial mycoses | Malassezia furfur (pityriasis versicolor), Trichosporon | | Cutaneous mycoses (dermatophytes) | Trichophyton, Microsporum, Epidermophyton | | Subcutaneous mycoses | Sporothrix schenckii, Madurella, Fonsecaea | | Systemic mycoses | Histoplasma, Coccidioides, Blastomyces | | Opportunistic mycoses | Candida, Aspergillus, Cryptococcus, Mucor, PCP | ## SUPERFICIAL AND SUBCUTANEOUS MYCOSES ### Dermatophytes – Classification and Lab Diagnosis | Genus | Infects | Key Species | |---|---|---| | Trichophyton | Hair, skin, nails (all three) | T. rubrum (most common worldwide), T. mentagrophytes | | Microsporum | Hair + skin (NOT nails) | M. canis (dogs/cats), M. audouinii | | Epidermophyton | Skin + nails (NOT hair) | E. floccosum | • Ecology: Anthropophilic (T. rubrum, E. floccosum), Zoophilic (M. canis), Geophilic (M. gypseum) • Tinea infections by site: T. capitis (scalp), T. corporis (body), T. pedis (athlete's foot), T. cruris (groin), T. unguium/onychomycosis (nails), T. barbae (beard) • Pathogenicity: Keratinophilic + keratinolytic enzymes; invade stratum corneum/hair/nail; inflammation via DTH to fungal antigens; do NOT invade living tissue • Lab diagnosis: KOH prep (branching septate hyphae; ectothrix/endothrix on hair); Wood's lamp (Microsporum sp. → green fluorescence); SDA culture + cycloheximide + chloramphenicol at 25-28°C for 1–3 weeks; identify by macroconidial morphology ### Mycetoma – Causative Agents • Eumycetoma (fungal black grains): Madurella mycetomatis; white grains: Pseudallescheria boydii, Acremonium • Actinomycetoma (bacterial): Nocardia brasiliensis, Actinomadura madurae • Lab Dx: KOH of pus+grains (fungal hyphae); culture on SDA; histopathology (Splendore-Hoeppli material) ## SYSTEMIC AND OPPORTUNISTIC MYCOSES ### Histoplasma capsulatum • Dimorphic: Yeast @37°C (2–5 µm; narrow-based budding; intracellular in macrophages); Mould @25°C (tuberculate macroconidia = pathognomonic; microconidia = infectious) • Pathogenesis: Inhalation of microconidia (bat/bird droppings, Mississippi/Ohio River valleys) → macrophages → yeast form → CMI → granuloma+calcification (most heal); disseminated disease in AIDS (CD4<150): hepatosplenomegaly, pancytopenia, oral ulcers ### Candida albicans • Morphology: Gram+ oval budding yeast (3–6 µm); pseudohyphae + true hyphae; chlamydospores on corn meal agar (terminal thick-walled spores) • Germ tube test (Reynolds-Braude phenomenon): C. albicans produces germ tubes in serum at 37°C/2–3 hrs (no constriction at origin); differentiates C. albicans from other Candida; also C. dubliniensis positive • Virulence: Als adhesins, hyphae (tissue invasion), SAPs (proteinases), biofilm, phenotypic switching • Diseases: Oral thrush, esophageal candidiasis, vulvovaginitis, onychomycosis, systemic candidiasis • Lab Dx: KOH/Gram stain (pseudohyphae+yeast); germ tube test; CHROMagar Candida; β-D-glucan; Candida mannan Ag; blood culture (BACTEC) ### Cryptococcal Meningitis – Lab Diagnosis • Causative agent: Cryptococcus neoformans (serotype A/D; CD4<100 in HIV); C. gattii (immunocompetent) • India ink: Negative staining; clear capsule halo around yeast; 60–80% sensitivity • CrAg LFA/Latex agglutination (serum+CSF): Detects polysaccharide capsule; >95% sensitive – MOST SENSITIVE TEST; used for HIV screening • Culture on SDA: Mucoid cream colonies; urease positive • Mucicarmine stain: Stains capsule pink in tissue • CSF: Elevated pressure; lymphocytic pleocytosis; elevated protein; low glucose ### Aspergillosis • A. fumigatus (most common), A. flavus, A. niger, A. terreus • ABPA: Type I+III hypersensitivity; asthma+eosinophilia+elevated IgE+central bronchiectasis • Aspergilloma: Fungal ball in pre-existing cavity (TB); hemoptysis; X-ray: air crescent sign • Invasive PA (IPA): Neutropenic patients; fever, hemoptysis; CT: HALO SIGN (hemorrhage around nodule) • Lab: KOH (septate hyphae, 45° acute branching); SDA (velvety green colonies); Galactomannan ELISA (serum; sensitive for IPA); β-D-glucan; CT/biopsy ### Opportunistic Fungi in HIV • PCP (Pneumocystis jirovecii): CD4<200; bilateral interstitial pneumonia ("ground-glass"); silver stain shows cysts in BAL; co-trimoxazole (treatment+prophylaxis) • Cryptococcus neoformans: CD4<100; meningitis (see above) • Candida: Esophageal candidiasis; fluconazole • Aspergillus: Invasive PA; voriconazole • Histoplasma: Disseminated; amphotericin B then itraconazole # PARASITOLOGY ## FLAGELLATES ### Leishmania donovani – LD Bodies and Kala Azar • LD bodies = Amastigotes: Intracellular in macrophages; 2–3 µm; oval; nucleus + kinetoplast (rod-shaped mitochondrial DNA – diagnostic); Giemsa: nucleus red, kinetoplast dark • Location: Spleen, liver, bone marrow, lymph nodes (RES) • Life cycle: Sandfly (Phlebotomus) ingests amastigotes → promastigotes in midgut → migrate to proboscis → bite human → promastigotes phagocytosed → amastigotes multiply → new macrophages → blood → disseminate • Kala Azar pathogenicity: Massive splenomegaly, hepatomegaly, pancytopenia (BM infiltration), hypergammaglobulinemia, double-quotidian fever, progressive wasting, skin darkening; PKDL (skin lesions after treatment = reservoir) • Lab Dx: Splenic aspirate (>95% sensitivity, Giemsa); bone marrow (safer); rK39 dipstick test (detects anti-Leishmania IgG; ~95–100% sensitivity; field rapid test); ELISA; PCR; Aldehyde (Napier's formol gel) test (non-specific); Montenegro test (negative in active VL – patient anergic; positive after cure) ### Giardia – Acute Giardiasis • Trophozoite: Pear-shaped, bilaterally symmetrical, 2 nuclei ("owl-face"), 4 pairs flagella; falling-leaf motility • Cyst: Oval, 4 nuclei, 4 flagella, 8–12 µm; infective stage • Lab Dx: Fresh stool (trophozoites in liquid stool; cysts in formed); formol-ether concentration; string test (Enterotest) for duodenal aspirate; Giardia Ag ELISA (stool) – most sensitive ~95%; DIF with monoclonal Ab • Findings: Offensive greasy floating stool (steatorrhoea); no blood/pus; malabsorption, bloating, flatulence ## SPOROZOA (MALARIA) ### Malaria – Peripheral Blood Smear Features | Feature | P. vivax | P. falciparum | P. malariae | P. ovale | |---|---|---|---|---| | RBC | Enlarged, pale | Normal/small | Normal | Slightly enlarged, oval | | Schüffner's dots | Present | Absent (Maurer's clefts) | Absent | Present (James' dots) | | Trophozoite | Amoeboid (irregular) | Ring only; multiple rings/RBC; accole forms | Band/ribbon | Compact | | Gametocyte | Round | BANANA/crescent-shaped (diagnostic) | Round | Round | | Cycle | 48 hrs (benign tertian) | 48 hrs (malignant tertian) | 72 hrs (quartan) | 48 hrs (oval tertian) | | Relapse | Yes (hypnozoites) | No (recrudescence only) | No | Yes (hypnozoites) | ### P. falciparum Complications • Cerebral malaria: Sequestration (PfEMP1 binds ICAM-1 on endothelium) → coma, convulsions (mortality 20%) • Severe anaemia: Haemolysis + bone marrow suppression • Blackwater fever: Massive haemolysis + haemoglobinuria → ARF (black urine) • Pulmonary oedema/ARDS, Hypoglycaemia, DIC, Hyperparasitaemia (>5%), Splenic rupture, Algid malaria (circulatory collapse) ### Malaria Lab Diagnosis • Thick film (Giemsa): Concentrates RBCs; better sensitivity for species detection • Thin film (Giemsa+methanol): Species morphology; best for P. falciparum banana gametocytes • RDT (rapid): HRP-2 (P. falciparum) or pLDH (all species); immunochromatographic; 15 min • PCR: Most sensitive; species + drug resistance genotyping • QBC: Acridine orange fluorescence; centrifuged buffy coat ## CESTODES (TAPEWORMS) ### Taenia saginata vs. Taenia solium | Feature | T. saginata (Beef – unarmed) | T. solium (Pork – armed) | |---|---|---| | Scolex | No hooks, no rostellum | Hooks (22–32) + rostellum | | Uterine branches | 15–30 lateral | 7–12 lateral | | Intermediate host | Cattle | Pig AND humans | | Cysticercosis in humans | NO | YES (neurocysticercosis) | | Danger | Intestinal only | Intestinal + CNS (fatal) | • Cysticercus cellulosae: Fluid-filled bladder (1 cm) with invaginated scolex; brain, muscle, eye; seizures; CT/MRI + EITB serology • Cysticercosis pathogenesis: Ingestion of T. solium eggs → oncospheres → penetrate gut → blood → brain/muscle → cysticercus; symptoms when cyst DIES (inflammation, edema, seizures) ### Hydatid Cyst (Echinococcus granulosus) • Definitive host: Dog (adult worm); Intermediate host: Sheep/cattle/humans • Sites: Liver (65–70%), Lung (20–25%), bone, brain • Structure: Pericyst (host fibrous) → Ectocyst (laminated, acellular – characteristic) → Endocyst (germinal layer – produces scolices/brood capsules/daughter cysts + hydatid sand) • Life cycle: Dog→eggs in faeces→ingested by sheep/humans→oncosphere penetrates gut→portal vein→liver→hydatid cyst; dog eats infected viscera→scolices→adult tapeworms ### Cestodes Classification | Cestode | Intermediate Host | Human Disease | |---|---|---| | Taenia saginata | Cattle | Intestinal tapeworm | | Taenia solium | Pig; Humans | Intestinal + Cysticercosis/NCC | | Echinococcus granulosus | Sheep/cattle/humans | Hydatid cyst | | Echinococcus multilocularis | Rodents | Alveolar echinococcosis | | Diphyllobothrium latum | Copepod→fish | B12 deficiency megaloblastic anaemia | | Hymenolepis nana | Humans (none needed) | Intestinal (dwarf tapeworm) | ## NEMATODES ### Ascaris lumbricoides • Morphology: Female 20–35 cm; male 15–30 cm; fertilized egg: oval, bile-stained mammillated cortex, 60×45 µm; unfertilized: longer, irregular • Life cycle: Embryonated egg ingested → hatch in duodenum → larvae→gut wall→portal vein→liver→heart→LUNGS (Löffler's syndrome) → cough up/swallowed → small intestine → adult worms → 200,000 eggs/day • Pathogenicity: Löffler's syndrome (larval, eosinophilic pneumonia), intestinal obstruction (worm bolus), malnutrition, ectopic ascariasis (biliary→colic/jaundice; pancreatic→pancreatitis) • Lab Dx: Stool wet mount (fertilized + unfertilized eggs); adult worm passage; X-ray (bunch of worms); USG/ERCP (ectopic) ### Hookworm (Ancylostoma duodenale / Necator americanus) • A. duodenale: 2 pairs ventral teeth; female 12 mm; Old World; sucks 0.2 mL blood/worm/day • N. americanus: Cutting plates; New World; 0.02 mL blood/worm/day • Egg: Oval, thin-shelled, 60×40 µm, 4–8 cell stage (identical for both species) • Life cycle: Eggs in soil → rhabditiform→filariform (L3, infective) larvae → SKIN PENETRATION (ground itch) → blood→lungs (Löffler's) → swallowed → intestine → adult • Pathogenesis: Ground itch (entry), Löffler's (lungs), iron deficiency anaemia (blood-sucking – major), hypoalbuminaemia/oedema • Lab Dx: Stool (eggs); concentration (formol-ether); Harada-Mori culture (larval ID); eosinophilia; microcytic hypochromic anaemia ### Enterobius vermicularis (Pinworm/Threadworm) • Life cycle: Eggs ingested→hatch in duodenum→adults in caecum/appendix→female migrates at night to perianal skin→lays 10,000 eggs→eggs embryonate in 6–8 hrs→autoinfection (scratching→hand→mouth) OR retroinfection • Pathogenicity: Nocturnal perianal pruritus (main symptom); vulvovaginitis; sleep disturbance • Lab Dx: Scotch tape (cellophane tape/Graham's) test – press tape on perianal region EARLY MORNING before bathing → microscopy → D-shaped egg (oval, flat on one side, contains larva) ### Wuchereria bancrofti – Morphology and Lab Diagnosis • Microfilariae: Sheathed (sheath stains pink Giemsa); nocturnal periodicity (max 10 PM–4 AM); no nuclei in tail tip (vs B. malayi: 2 distinct tail nuclei); 244–296 µm • Adults: Thread-like; reside in lymphatics; cause lymphoedema/elephantiasis, hydrocele • Lab Dx: Thick blood film (10 PM–2 AM) + Giemsa stain; Knott's concentration (blood+formalin); Og4C3 ELISA (circulating filarial antigen); ICT card test; USG "filarial dance sign" (live adult worms in scrotal lymphatics – pathognomonic) ### Strongyloides stercoralis Hyperinfection • Occurs in immunocompromised (corticosteroids, HTLV-1, AIDS, transplant) • Massive amplification of autoinfection cycle → larvae carry gut bacteria through intestinal wall → Gram-negative sepsis/meningitis (most fatal complication) • Features: Haemorrhagic enteritis, pneumonitis, larva currens (rapidly migrating urticarial tracks) • Lab Dx: Stool for rhabditiform larvae; Baermann technique; serology; larvae in BAL/sputum • Treatment: Ivermectin (drug of choice); Albendazole ### Guinea Worm (Dracunculus medinensis) – Life Cycle • Drink infected water (Cyclops with L3) → Cyclops digested → L3 penetrates gut wall → body cavity → mature in subcutaneous tissue (12–18 months) → gravid female migrates to skin → blister on leg → ruptures in water → releases L1 larvae → Cyclops ingests L1 → L2→L3 in Cyclops • Extraction: Roll worm slowly around stick (1–2 cm/day); never break worm → anaphylaxis • Control: Filter drinking water; temephos (Abate); health education ### Occult Filariasis • Clinical filariasis WITHOUT detectable microfilariae in blood • Tropical Pulmonary Eosinophilia (TPE): Vigorous IgE response destroys microfilariae in lungs; paroxysmal nocturnal cough+wheeze; bilateral mottling on X-ray; marked eosinophilia; high IgE; anti-filarial IgE and IgG • Diagnosis: Eosinophilia + high IgE + anti-filarial Ab (IgG4 ELISA) + response to DEC ### Four Parasites Causing Anaemia • Hookworm (A. duodenale/Necator): Iron deficiency anaemia (blood-sucking) • Plasmodium species: Haemolytic anaemia • Diphyllobothrium latum: B12 deficiency megaloblastic anaemia (competes for B12 in ileum) • Leishmania donovani: Anaemia from hypersplenism + bone marrow suppression ### Ectopic Ascariasis • Biliary (most common): Worm through ampulla of Vater → biliary colic, obstructive jaundice, cholangitis • Pancreatic duct: Pancreatitis; Appendix: Appendicitis; Peritoneum: Perforation + peritonitis • Dx: USG/ERCP (hyperechoic elongated tube in bile duct); Tx: Albendazole + ERCP extraction ## DIAGNOSTIC PROCEDURES ### Stool Concentration Methods | Method | Type | Best for | |---|---|---| | ZnSO₄ flotation (Faust's) | Flotation (SG 1.18) | Protozoan cysts (Giardia, Entamoeba), hookworm eggs | | Saturated NaCl flotation | Flotation (SG 1.20) | Hookworm, Enterobius eggs | | Formol-ether (Ritchie's) – MOST USED | Sedimentation | ALL parasites; operculated eggs; thick-shelled eggs | | Simple gravity sedimentation | Sedimentation | Basic; rarely used | | Baermann technique | Special | Strongyloides larvae | | Knott's concentration | Special | Blood microfilariae | ### Parasites Detected in Blood Smear • Plasmodium sp. (ring trophozoites, mature stages, gametocytes) – Giemsa thick+thin film • Microfilariae – W. bancrofti, B. malayi (nocturnal); Loa loa (diurnal); Giemsa thick film • Trypanosoma brucei (African sleeping sickness) – trypomastigotes in buffy coat • Trypanosoma cruzi (Chagas disease) – trypomastigotes in acute phase • Babesia sp. – intraerythrocytic rings; "Maltese cross/tetrad" forms; NO haemozoin • Leishmania donovani – amastigotes in buffy coat/bone marrow (rarely peripheral blood) """ # ── Parse ──────────────────────────────────────────────────────────────────── def parse(raw): items = [] for line in raw.splitlines(): s = line.strip() if not s: continue if re.match(r'^# (?!#)', s): items.append(('h1', s[2:].strip())) elif re.match(r'^## (?!#)', s): items.append(('h2', s[3:].strip())) elif s.startswith('### '): items.append(('h3', s[4:].strip())) elif re.match(r'^\|.+\|', s): cells = [c.strip() for c in s.split('|') if c.strip()] if cells and not re.match(r'^[-:]+$', cells[0]): items.append(('tr', cells)) elif re.match(r'^[•\-\*] ', s) or re.match(r'^\d+\. ', s): items.append(('bul', '• ' + clean(re.sub(r'^[•\-\*\d]+\.?\s*','',s)))) elif s == '---': pass else: items.append(('body', clean(s))) return items def to_fl(kind, text): if kind == 'h1': bg = get_sec_color(text) st = ParagraphStyle('h1x', fontName='Helvetica-Bold', fontSize=7.5, leading=9.5, textColor=colors.white, backColor=bg, borderPadding=(2,5,2,5), spaceAfter=1, spaceBefore=4) return Paragraph(f' ■ {text}', st) elif kind == 'h2': bg = get_sec_color(text) st = ParagraphStyle('h2x', fontName='Helvetica-Bold', fontSize=6.8, leading=8.5, textColor=colors.white, backColor=bg, borderPadding=(1.5,4,1.5,4), spaceAfter=0.8, spaceBefore=2.5) return Paragraph(f' {text}', st) elif kind == 'h3': return Paragraph( f'<font color="#bf360c">▌</font> <b>{text}</b>', ST['h3']) elif kind == 'bul': return Paragraph(text, ST['bul']) else: return Paragraph(text, ST['body']) def build(items): fls = []; i = 0 while i < len(items): kind, text = items[i] if kind == 'tr': rows = [] while i < len(items) and items[i][0] == 'tr': rows.append(items[i][1]); i += 1 if not rows: continue ncols = max(len(r) for r in rows) cw = [(COL_W - 6) / ncols] * ncols th = ParagraphStyle('th', fontName='Helvetica-Bold', fontSize=5.2, leading=6.5, textColor=colors.white) td = ParagraphStyle('td', fontName='Helvetica', fontSize=5.2, leading=6.5) tdata = [] for ri, row in enumerate(rows): while len(row) < ncols: row.append('') row = row[:ncols] tdata.append([Paragraph(c, th if ri==0 else td) for c in row]) t = Table(tdata, colWidths=cw, repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(-1,0), C_TEAL), ('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white, C_LGREY]), ('GRID',(0,0),(-1,-1),0.3, colors.HexColor('#b0bec5')), ('LEFTPADDING',(0,0),(-1,-1), 2), ('RIGHTPADDING',(0,0),(-1,-1), 2), ('TOPPADDING',(0,0),(-1,-1), 1), ('BOTTOMPADDING',(0,0),(-1,-1), 1), ('VALIGN',(0,0),(-1,-1),'TOP'), ])) fls.append(t); fls.append(Spacer(1, 1.5)) else: fls.append(to_fl(kind, text)); i += 1 return fls class Doc2Col(BaseDocTemplate): def __init__(self, fn, **kw): super().__init__(fn, **kw) frames = [] for col in range(N_COLS): x = MARGIN + col * (COL_W + COL_GAP) frames.append(Frame(x, MARGIN+5*mm, COL_W, H-2*MARGIN-14*mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id=f'c{col}')) self.addPageTemplates([PageTemplate(id='2c', frames=frames, onPage=self.deco)]) def deco(self, canvas, doc): canvas.saveState() # Header bar canvas.setFillColor(C_NAVY) canvas.rect(MARGIN, H-9*mm, W-2*MARGIN, 7.5*mm, fill=1, stroke=0) # Colour accent strip under header strip_colors = [ colors.HexColor('#1565c0'), # Immunology blue colors.HexColor('#4a148c'), # Virology purple colors.HexColor('#1b5e20'), # Mycology green colors.HexColor('#bf360c'), # Parasitology orange ] strip_w = (W-2*MARGIN)/4 for si, sc in enumerate(strip_colors): canvas.setFillColor(sc) canvas.rect(MARGIN + si*strip_w, H-9.9*mm, strip_w, 1*mm, fill=1, stroke=0) # Header text canvas.setFillColor(colors.white) canvas.setFont('Helvetica-Bold', 7) canvas.drawString(MARGIN+3*mm, H-5.5*mm, 'MICROBIOLOGY PAPER II | Quick Revision Guide | Apurva Shastri') canvas.setFont('Helvetica', 6) canvas.drawRightString(W-MARGIN, H-5.5*mm, f'Page {doc.page}') canvas.setFont('Helvetica', 5.5) canvas.setFillColor(colors.HexColor('#b2ebf2')) canvas.drawString(MARGIN+3*mm, H-8*mm, 'Immunology · Virology · Mycology · Parasitology') # Footer canvas.setFillColor(colors.HexColor('#1a237e')) canvas.rect(MARGIN, MARGIN, W-2*MARGIN, 4.5*mm, fill=1, stroke=0) # Colour footer strip for si, sc in enumerate(strip_colors): canvas.setFillColor(sc) canvas.rect(MARGIN + si*strip_w, MARGIN+4.5*mm, strip_w, 0.6*mm, fill=1, stroke=0) canvas.setFillColor(colors.white) canvas.setFont('Helvetica', 5.2) canvas.drawCentredString(W/2, MARGIN+1.5*mm, 'Blue=Immunology | Purple=Virology | Green=Mycology | Orange=Parasitology') # Column divider mid_x = MARGIN + COL_W + COL_GAP/2 canvas.setStrokeColor(colors.HexColor('#90a4ae')) canvas.setLineWidth(0.5) canvas.setDash(3, 2) canvas.line(mid_x, MARGIN+5.5*mm, mid_x, H-10*mm) canvas.restoreState() items = parse(CONTENT) fls = build(items) header = [ Spacer(1, 1*mm), Paragraph('MICROBIOLOGY PAPER II – QUICK REVISION', ST['title']), Paragraph('Apurva Shastri | Professional Exam | Immunology · Virology · Mycology · Parasitology', ST['sub']), HRFlowable(width=COL_W, thickness=1.5, color=C_NAVY, spaceAfter=3), ] out = '/home/daytona/workspace/Microbiology_Paper2_Revision.pdf' doc = Doc2Col(out, pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=10*mm, bottomMargin=7*mm) doc.build(header + fls) from pypdf import PdfReader r = PdfReader(out) print(f'Pages: {len(r.pages)}') print(f'Size: {os.path.getsize(out)/1024:.1f} KB') print('Done:', out) PYEOF python3 /home/daytona/workspace/build_paper2.py