Let's all kindly submit the following data for Dr febby halubono Senior Resident Medical Officer for 2027 plan. Study Leave -_ - Program of study is urology - Duration of 4years - Institution of study Levy mwanawasa
CARRY IT OUT
Create a formal study-leave request letter
MAKE IT IN WORD DOCUMENT
~/
mkdir -p "/tmp/workspace/study-leave-letter/output" "/tmp/workspace/study-leave-letter/src" && python3 - <<'PY' from docx import Document from docx.shared import Inches, Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml import OxmlElement from docx.oxml.ns import qn from pathlib import Path out = Path('/tmp/workspace/study-leave-letter/output/Dr_Febby_Halubono_Study_Leave_Request_2027.docx') doc = Document() section = doc.sections[0] section.top_margin = Inches(1) section.bottom_margin = Inches(1) section.left_margin = Inches(1) section.right_margin = Inches(1) normal = doc.styles['Normal'] normal.font.name = 'Arial' normal._element.rPr.rFonts.set(qn('w:eastAsia'), 'Arial') normal.font.size = Pt(12) normal.paragraph_format.space_after = Pt(9) normal.paragraph_format.line_spacing = 1.15 # Add footer page number footer = section.footer.paragraphs[0] footer.alignment = WD_ALIGN_PARAGRAPH.CENTER run = footer.add_run('Page ') fldChar1 = OxmlElement('w:fldChar'); fldChar1.set(qn('w:fldCharType'), 'begin') instrText = OxmlElement('w:instrText'); instrText.set(qn('xml:space'), 'preserve'); instrText.text = 'PAGE' fldChar2 = OxmlElement('w:fldChar'); fldChar2.set(qn('w:fldCharType'), 'end') run._r.append(fldChar1); run._r.append(instrText); run._r.append(fldChar2) p = doc.add_paragraph('16 September 2026') p.paragraph_format.space_after = Pt(18) for line in ['The Medical Superintendent / Director Human Resources', '[Name of Hospital/Institution]', '[Institution Address]']: p = doc.add_paragraph(line) p.paragraph_format.space_after = Pt(0) doc.add_paragraph() p = doc.add_paragraph() r = p.add_run('RE: REQUEST FOR STUDY LEAVE FOR POSTGRADUATE TRAINING IN UROLOGY') r.bold = True r.underline = True p.paragraph_format.space_after = Pt(16) p = doc.add_paragraph('Dear Sir/Madam,') p.paragraph_format.space_after = Pt(12) body = [ 'I respectfully write to request approval for study leave commencing in 2027 to undertake postgraduate training in Urology at Levy Mwanawasa Medical University.', 'The proposed programme will run for a period of four years. The training will enable me to develop specialist knowledge and clinical competencies in urology, which I will apply to strengthen the delivery of urological services at the institution upon completion of the programme.', 'I kindly request that my application be considered and approved in accordance with the applicable institutional policies and procedures. I am available to provide any supporting documentation or further information required in relation to this application.', 'Thank you for your consideration.' ] for text in body: p = doc.add_paragraph(text) p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY p.paragraph_format.first_line_indent = Inches(0.3) p.paragraph_format.space_after = Pt(12) p = doc.add_paragraph('Yours faithfully,') p.paragraph_format.space_before = Pt(12) p.paragraph_format.space_after = Pt(36) p = doc.add_paragraph() r = p.add_run('Dr. Febby Halubono') r.bold = True p = doc.add_paragraph('Senior Resident Medical Officer') p.paragraph_format.space_after = Pt(0) p = doc.add_paragraph('[Department/Unit]') p.paragraph_format.space_after = Pt(0) p = doc.add_paragraph('[Hospital/Institution]') p.paragraph_format.space_after = Pt(0) p = doc.add_paragraph('[Phone Number / Email]') p.paragraph_format.space_after = Pt(0) doc.core_properties.title = 'Study Leave Request for 2027' doc.core_properties.author = 'Dr. Febby Halubono' doc.save(out) print(out) PY python3 - <<'PY' from docx import Document p='/tmp/workspace/study-leave-letter/output/Dr_Febby_Halubono_Study_Leave_Request_2027.docx' d=Document(p) print('Created:', p) print('Paragraphs:', len(d.paragraphs)) print('Text contains:', ' | '.join(x.text for x in d.paragraphs if x.text.strip())[:500]) PY
Dr Febby Halubono Study Leave Request 2027
Word Document · DOCX
MAKE MCQ QUESTIONS 50 QUESTIONS AS SECTION A AND SECTION B AND C SHOULD BE CLINICAL SCENARIOS MAKE IT AT THE LEVEL OF USMLE LEVEL
How should the 50 questions be distributed across the three sections? · What format would you like for the exam?
Dr Febby Halubono Study Leave Request 2027
Word Document · DOCX
~/
python3 - <<'PY' from pptx import Presentation from pathlib import Path files = [ '/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/NEONATOLOGY INTRO.pptx', '/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/EXAMINATION OF THE NEW BORN (3).pptx', '/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/Asthma-WPS Office (2).pptx' ] outdir = Path('/tmp/workspace/usmle-mcq-exam/source') outdir.mkdir(parents=True, exist_ok=True) for f in files: prs=Presentation(f) out = outdir/(Path(f).stem + '.txt') with out.open('w', encoding='utf-8') as h: h.write(f'TITLE: {Path(f).name}\nSLIDES: {len(prs.slides)}\n\n') for i, slide in enumerate(prs.slides,1): texts=[] for sh in slide.shapes: if getattr(sh,'has_text_frame',False): s=sh.text_frame.text.strip() if s: texts.append(s) if getattr(sh,'has_table',False): for row in sh.table.rows: texts.append(' | '.join(c.text.strip() for c in row.cells)) h.write(f'--- Slide {i} ---\n'+'\n'.join(texts)+'\n\n') print(out) PY
asthma AND child
AAP newborn examination pediatric asthma diagnosis management clinical guideline
Re-upload the PowerPoints and create the 50-question exam
~/
GINA 2025 asthma children management PDF diagnosis treatment
asthma AND child
~/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09
mkdir -p "/tmp/workspace/usmle-mcq-exam/source" "/tmp/workspace/usmle-mcq-exam/output" && python3 - <<'PY' from pptx import Presentation from pathlib import Path files = [ '/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/NEONATOLOGY INTRO.pptx', '/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/EXAMINATION OF THE NEW BORN (3).pptx', '/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/Asthma-WPS Office (2).pptx' ] outdir = Path('/tmp/workspace/usmle-mcq-exam/source') for f in files: prs=Presentation(f) out = outdir/(Path(f).stem + '.txt') with out.open('w', encoding='utf-8') as h: h.write(f'TITLE: {Path(f).name}\nSLIDES: {len(prs.slides)}\n\n') for i, slide in enumerate(prs.slides,1): texts=[] for sh in slide.shapes: if getattr(sh,'has_text_frame',False): s=sh.text_frame.text.strip() if s: texts.append(s) if getattr(sh,'has_table',False): for row in sh.table.rows: texts.append(' | '.join(c.text.strip() for c in row.cells)) h.write(f'--- Slide {i} ---\n'+'\n'.join(texts)+'\n\n') print(f'{Path(f).name}: {len(prs.slides)} slides -> {out}') PY
python3 - <<'PY' from docx import Document from docx.shared import Inches, Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.section import WD_SECTION from docx.enum.style import WD_STYLE_TYPE from docx.oxml import OxmlElement from docx.oxml.ns import qn from pathlib import Path out=Path('/tmp/workspace/usmle-mcq-exam/output/Neonatology_Newborn_Examination_Asthma_USMLE_MCQ_Exam.docx') questions = [ ('A', 'A term newborn has an Apgar score of 8 at 1 minute. Which finding is included in the Apgar assessment?', ['Serum glucose concentration','Heart rate','Head circumference','Moro reflex symmetry','Gestational age'], 'B', 'Apgar scoring assesses Appearance, Pulse, Grimace, Activity, and Respiration. Heart rate is the Pulse component.'), ('A', 'The principal physiologic event that permits the normal transition from fetal to neonatal circulation is:', ['Increased pulmonary vascular resistance after the first breath','Closure of the ductus arteriosus before delivery','A marked fall in pulmonary vascular resistance with lung expansion','Increased right-to-left shunting across the foramen ovale','Cessation of placental blood flow before lung aeration'], 'C', 'Lung expansion and oxygenation lower pulmonary vascular resistance, increase pulmonary blood flow, and facilitate functional closure of fetal shunts.'), ('A', 'A newborn is classified as preterm when delivered before which gestational age?', ['34 completed weeks','35 completed weeks','36 completed weeks','37 completed weeks','38 completed weeks'], 'D', 'Preterm birth is delivery before 37 completed weeks of gestation.'), ('A', 'Which physical finding is most consistent with a small-for-gestational-age newborn after chronic placental insufficiency?', ['Diffuse edema and macroglossia','Reduced subcutaneous fat and relatively large head','Marked generalized hypotonia and a single palmar crease','Bulging anterior fontanelle and hepatomegaly','Wide-spaced nipples and webbed neck'], 'B', 'Chronic fetal undernutrition causes asymmetric growth restriction with reduced fat and muscle mass and relative head sparing.'), ('A', 'Which maternal condition is most strongly associated with neonatal hypoglycemia due to fetal hyperinsulinemia?', ['Chronic hypertension','Diabetes mellitus','Hypothyroidism','Iron deficiency anemia','Systemic lupus erythematosus'], 'B', 'Maternal hyperglycemia causes fetal hyperinsulinemia. After delivery, glucose supply stops while insulin remains elevated.'), ('A', 'A newborn examination should include red reflex testing primarily to screen for:', ['Conductive hearing loss','Congenital cataract or retinoblastoma','Glaucoma caused by increased intraocular pressure','Retinopathy of prematurity','Strabismus due to cranial nerve palsy'], 'B', 'An absent or asymmetric red reflex can indicate media opacity such as cataract or a leukocoria-producing lesion such as retinoblastoma.'), ('A', 'The Ortolani maneuver is used to detect developmental dysplasia of the hip by:', ['Attempting to reduce a posteriorly dislocated femoral head','Attempting to dislocate an unstable femoral head','Measuring acetabular depth by palpation','Assessing femoral nerve function','Detecting hip flexion contractures'], 'A', 'Ortolani reduces a dislocated hip with abduction and anterior lifting. Barlow provokes dislocation of an unstable hip.'), ('A', 'Which neonatal reflex normally disappears first?', ['Moro reflex','Palmar grasp reflex','Rooting reflex','Stepping reflex','Tonic neck reflex'], 'D', 'The stepping reflex generally disappears by about 2 months, earlier than Moro, rooting, palmar grasp, and tonic neck reflexes.'), ('A', 'A sacral dimple requires further evaluation for occult spinal dysraphism when it is:', ['Located within the gluteal cleft and has a visible base','Small and less than 2.5 cm from the anus','Associated with a hair tuft or skin discoloration','Present in an otherwise normal infant','Less than 5 mm in diameter'], 'C', 'Atypical dimples, especially those with hair tuft, hemangioma, skin tag, high location, or nonvisualized base, may indicate occult spinal dysraphism.'), ('A', 'Which finding is most characteristic of physiologic jaundice in a term newborn?', ['Onset in the first 12 hours after birth','Predominantly conjugated hyperbilirubinemia','Onset after 24 hours with a peak around days 3 to 5','Persistence beyond 3 weeks with pale stools','Rapid rise associated with anemia'], 'C', 'Physiologic unconjugated jaundice begins after 24 hours and peaks around days 3 to 5 in term infants.'), ('A', 'Asthma is best defined as:', ['Irreversible destruction of alveolar walls','Chronic airway inflammation with variable expiratory airflow limitation','Restrictive lung disease caused by interstitial fibrosis','Bacterial infection of the small airways','Fixed upper-airway obstruction'], 'B', 'Asthma is characterized by variable respiratory symptoms and variable expiratory airflow limitation, usually related to airway inflammation and bronchial hyperresponsiveness.'), ('A', 'Which finding provides the strongest objective support for asthma in a cooperative school-aged child?', ['A low FEV1/FVC ratio that improves after bronchodilator','A normal chest radiograph','Peripheral eosinophilia alone','Elevated erythrocyte sedimentation rate','A positive tuberculin skin test'], 'A', 'Demonstration of variable airflow limitation, such as bronchodilator reversibility on spirometry, supports asthma.'), ('A', 'During an acute asthma exacerbation, bronchial smooth-muscle constriction most directly causes:', ['Reduced airway resistance','Increased expiratory airflow','Air trapping and prolonged expiration','Increased pulmonary compliance','A restrictive spirometry pattern'], 'C', 'Narrowed airways increase expiratory resistance and promote air trapping, producing prolonged expiration and wheeze.'), ('A', 'Which medication is a short-acting beta2-agonist used for rapid relief of bronchospasm?', ['Albuterol','Budesonide','Montelukast','Omalizumab','Tiotropium'], 'A', 'Albuterol provides rapid bronchodilation and is used as a reliever medication.'), ('A', 'The key anti-inflammatory controller medication for persistent asthma is:', ['Inhaled corticosteroid','Oral antibiotic','Inhaled short-acting beta2-agonist','Oral antihistamine alone','Mucolytic therapy'], 'A', 'Inhaled corticosteroids are the preferred long-term controller treatment for persistent asthma.'), ('A', 'Which exposure is a common trigger of acute asthma symptoms?', ['Cold air','High dietary calcium intake','Sunlight exposure','Routine vaccination','Mild dehydration'], 'A', 'Cold air, viral infection, allergen exposure, exercise, smoke, and airway irritants are common triggers.'), ('A', 'A “silent chest” during an asthma attack is most concerning because it suggests:', ['Complete clinical recovery','Severe airflow obstruction with minimal air movement','An upper respiratory tract infection only','Normal findings in mild intermittent asthma','A nonpulmonary cause of dyspnea'], 'B', 'Very poor air movement can eliminate audible wheeze and signals potentially life-threatening obstruction.'), ('A', 'Which spirometric pattern is typical of obstructive airway disease?', ['Increased FEV1/FVC ratio','Decreased FEV1/FVC ratio','Decreased total lung capacity with normal ratio','Increased diffusing capacity only','Normal forced expiratory flow in all cases'], 'B', 'Obstruction reduces FEV1 disproportionately relative to FVC, lowering the FEV1/FVC ratio.'), ('A', 'Which asthma medication should be avoided in a patient with aspirin-exacerbated respiratory disease?', ['Aspirin','Inhaled corticosteroid','Albuterol','Ipratropium','Leukotriene receptor antagonist'], 'A', 'Aspirin and other COX-1 inhibiting NSAIDs can trigger severe bronchospasm in susceptible patients.'), ('A', 'The most appropriate first response to a stable patient with asthma whose symptoms remain uncontrolled is to:', ['Immediately label the patient as having severe refractory asthma','Assess inhaler technique, adherence, and trigger exposure','Stop all controller medication','Order a chest radiograph as the only next step','Start chronic oral corticosteroids'], 'B', 'Before escalating therapy, confirm the diagnosis, assess adherence and inhaler technique, and address modifiable risk factors and exposures.'), ('B', 'A 39-week newborn is cyanotic at 18 hours of life. Oxygen saturation is 82% in the right hand and 92% in a foot. There is no murmur. Which condition is most likely?', ['Persistent pulmonary hypertension with right-to-left ductal shunting','Coarctation of the aorta','Ventricular septal defect','Tricuspid atresia with decreased pulmonary flow','Patent ductus arteriosus with left-to-right shunting'], 'A', 'Preductal saturation lower than postductal saturation suggests right-to-left shunting through the ductus arteriosus into the descending aorta, seen with pulmonary hypertension or certain ductal-dependent lesions.'), ('B', 'A 2-day-old boy has bilious vomiting and progressive abdominal distension. He has not passed meconium. Abdominal radiography shows dilated bowel loops. What is the most appropriate next step?', ['Reassure and observe for physiologic reflux','Give an oral feeding challenge','Urgent surgical evaluation after stabilization','Begin phototherapy','Perform a sweat chloride test as the only test'], 'C', 'Bilious emesis in a newborn is intestinal obstruction until proven otherwise and requires prompt stabilization and surgical assessment, including exclusion of malrotation with volvulus.'), ('B', 'A term newborn has a cephalohematoma noted several hours after vaginal delivery. The swelling does not cross suture lines. Which complication should be monitored most closely?', ['Hypoglycemia','Unconjugated hyperbilirubinemia','Congenital hypothyroidism','Polycythemia from placental transfusion','Necrotizing enterocolitis'], 'B', 'Breakdown of blood in a cephalohematoma increases bilirubin production and can worsen unconjugated jaundice.'), ('B', 'A 3-day-old infant has poor feeding, lethargy, temperature instability, and respiratory distress. Which diagnosis should be presumed while evaluation is initiated?', ['Neonatal sepsis','Physiologic jaundice','Colic','Gastroesophageal reflux','Infant dyschezia'], 'A', 'Neonatal sepsis often presents nonspecifically. Ill newborns require immediate assessment and empiric treatment after cultures when possible.'), ('B', 'A newborn has a harsh systolic murmur, weak femoral pulses, and lower-extremity blood pressure lower than right-arm blood pressure. Which diagnosis is most likely?', ['Coarctation of the aorta','Patent foramen ovale','Atrial septal defect','Transposition of the great arteries','Tetralogy of Fallot'], 'A', 'Weak or delayed femoral pulses and upper-to-lower extremity pressure gradient are classic for coarctation.'), ('B', 'A 2-week-old boy has forceful nonbilious vomiting after feeds and remains hungry. He is mildly dehydrated. Which acid-base abnormality is most likely?', ['High-anion-gap metabolic acidosis','Non-anion-gap metabolic acidosis','Hypochloremic, hypokalemic metabolic alkalosis','Respiratory acidosis','Respiratory alkalosis'], 'C', 'Hypertrophic pyloric stenosis causes loss of gastric hydrochloric acid, leading to hypochloremic metabolic alkalosis and often hypokalemia.'), ('B', 'A term infant has poor feeding, diaphoresis during feeds, tachypnea, and hepatomegaly at 4 weeks of age. A holosystolic murmur is heard at the left lower sternal border. Which mechanism best explains the symptoms?', ['Right-to-left shunting causing cyanosis','Left-to-right shunting causing pulmonary overcirculation','Closure of the foramen ovale causing venous congestion','Obstruction of pulmonary venous return','Reduced systemic vascular resistance due to sepsis'], 'B', 'A significant ventricular septal defect produces left-to-right shunting and symptoms of heart failure as pulmonary vascular resistance falls over weeks after birth.'), ('B', 'A newborn has ambiguous genitalia, vomiting, dehydration, hyponatremia, and hyperkalemia on day 8 of life. Which enzyme deficiency is most likely?', ['21-hydroxylase deficiency','11-beta-hydroxylase deficiency','17-alpha-hydroxylase deficiency','5-alpha-reductase deficiency','Aromatase deficiency'], 'A', 'Salt-wasting congenital adrenal hyperplasia from 21-hydroxylase deficiency causes cortisol and aldosterone deficiency with androgen excess.'), ('B', 'A 4-year-old has recurrent episodes of cough and wheeze, mostly with viral infections. Between episodes, examination is normal. Symptoms improve promptly after inhaled albuterol. What is the best interpretation?', ['Asthma cannot be diagnosed before age 5 years','The pattern supports a clinical diagnosis of asthma after alternative causes are considered','Bronchiolitis is the only possible diagnosis','Spirometry is required before any therapeutic trial','The child has fixed airway obstruction'], 'B', 'In young children, asthma may be diagnosed pragmatically using recurrent wheeze, exclusion of alternatives, and a timely response to asthma treatment.'), ('B', 'An 8-year-old with asthma wakes with cough 3 nights each week and uses albuterol most days. There have been no hospitalizations. What is the best next management step?', ['Continue reliever-only treatment','Begin or step up daily inhaled corticosteroid-containing controller therapy','Start an oral antibiotic','Stop albuterol completely','Use oral corticosteroids every day indefinitely'], 'B', 'Frequent symptoms and nocturnal awakening indicate poor control. Controller therapy with an inhaled corticosteroid should be initiated or stepped up after technique and adherence are checked.'), ('B', 'A 12-year-old develops wheeze, urticaria, and hypotension minutes after eating peanuts. Which is the best immediate treatment?', ['Nebulized albuterol alone','Intramuscular epinephrine','Oral antihistamine alone','Inhaled corticosteroid','Intravenous antibiotics'], 'B', 'This is anaphylaxis. Intramuscular epinephrine is first-line treatment; albuterol may be an adjunct for bronchospasm.'), ('B', 'A 10-year-old with asthma arrives speaking in single words with tachypnea, accessory muscle use, and oxygen saturation of 88% on room air. Breath sounds are markedly diminished bilaterally. What is the most appropriate immediate management?', ['Discharge after one dose of oral antihistamine','Supplemental oxygen, repeated inhaled short-acting beta2-agonist, and systemic corticosteroid','Chest physiotherapy only','Daily inhaled corticosteroid without acute treatment','Observe without intervention because wheezing is absent'], 'B', 'Severe exacerbation with hypoxemia and diminished air movement requires oxygen, prompt inhaled bronchodilators, systemic corticosteroids, and escalation as needed.'), ('B', 'A 9-year-old has episodic dyspnea during soccer. Spirometry at baseline is normal. Which test is most useful to support exercise-induced bronchoconstriction?', ['Exercise challenge showing a fall in FEV1','Chest CT scan','Sputum bacterial culture','Serum total IgE alone','Echocardiogram'], 'A', 'A fall in FEV1 after exercise challenge supports exercise-induced bronchoconstriction.'), ('B', 'A 14-year-old with asthma has recurrent symptoms despite a prescribed inhaled corticosteroid. He uses the inhaler only when short of breath and demonstrates incorrect technique. What is the most appropriate intervention?', ['Increase medication dose before education','Review adherence and demonstrate correct inhaler technique','Replace all inhalers with antibiotics','Diagnose treatment-resistant asthma immediately','Stop the inhaled corticosteroid'], 'B', 'Nonadherence and incorrect technique are common causes of poor asthma control and should be corrected before treatment escalation.'), ('B', 'A 7-year-old has a chronic cough, wheeze, and daily exposure to cigarette smoke at home. What intervention has the greatest likelihood of reducing asthma morbidity?', ['Eliminate secondhand smoke exposure','Use a cough suppressant nightly','Obtain a routine chest radiograph every month','Avoid all physical activity','Start prophylactic antibiotics'], 'A', 'Tobacco smoke is an important modifiable trigger and risk factor. Eliminating exposure is a central component of asthma management.'), ('C', 'A 38-week newborn has severe respiratory distress immediately after birth, a scaphoid abdomen, and decreased breath sounds on the left. Chest radiograph shows bowel loops in the left hemithorax. What is the best initial management?', ['Bag-mask ventilation until oxygen saturation normalizes','Immediate surgical repair before stabilization','Endotracheal intubation with gastric decompression and gentle ventilation','Needle thoracostomy on the left','Oral feeding to assess swallowing'], 'C', 'Congenital diaphragmatic hernia requires intubation, gastric decompression, and gentle ventilatory support. Bag-mask ventilation can distend bowel and worsen lung compression.'), ('C', 'A newborn born after prolonged rupture of membranes develops respiratory distress. Blood culture later grows group B Streptococcus. Which mechanism most likely predisposed this newborn?', ['Transplacental spread of maternal IgG','Ascending infection from the maternal genital tract','Postnatal exposure through breast milk','Insect-borne transmission','Reactivation of latent neonatal infection'], 'B', 'Early-onset group B Streptococcus disease is usually acquired through ascending infection or exposure to colonized maternal genital tract during birth.'), ('C', 'A 1-day-old infant has jitteriness and poor feeding. Bedside glucose is 28 mg/dL. The mother had poorly controlled diabetes. After prompt treatment, which mechanism most directly caused the hypoglycemia?', ['Deficient glucagon secretion due to maternal insulin crossing placenta','Persistent fetal hyperinsulinemia after interruption of maternal glucose supply','Increased renal glucose loss','Cortisol excess','Reduced glycogen storage due to starvation'], 'B', 'Maternal insulin does not cross the placenta. Fetal pancreatic hyperinsulinemia persists briefly after delivery while maternal glucose transfer abruptly stops.'), ('C', 'A 36-hour-old newborn has jaundice, anemia, reticulocytosis, and a positive direct antiglobulin test. The mother is blood type O and the infant is blood type A. What is the pathogenesis?', ['Maternal IgG against fetal A antigen causing hemolysis','Maternal IgM against fetal Rh antigen crossing the placenta','Deficient bilirubin conjugation alone','Inherited absence of red-cell spectrin','Infection causing cholestasis'], 'A', 'ABO hemolytic disease occurs when maternal IgG anti-A or anti-B antibodies cross the placenta and hemolyze fetal red cells.'), ('C', 'A 5-day-old newborn has fever, irritability, poor feeding, and vesicular lesions on the scalp. The mother had genital lesions near delivery. Which treatment should be started immediately?', ['Intravenous acyclovir','Oral amoxicillin','Phototherapy','Topical antifungal therapy','Intravenous immunoglobulin only'], 'A', 'Possible neonatal herpes simplex virus infection requires immediate IV acyclovir because delay can lead to disseminated or CNS disease.'), ('C', 'A newborn has recurrent apnea, temperature instability, poor perfusion, and metabolic acidosis. What is the most appropriate initial approach?', ['Wait for culture results before treating','Obtain cultures and promptly begin empiric intravenous antibiotics','Provide only supplemental oxygen','Treat with an oral bronchodilator','Assume the symptoms are physiologic prematurity'], 'B', 'This presentation is concerning for sepsis. Cultures should be obtained promptly, followed by empiric antibiotics without waiting for results.'), ('C', 'A 2-day-old infant has tachypnea and cyanosis that do not improve with supplemental oxygen. Chest radiograph shows a narrow mediastinum. Which lesion is most likely?', ['Transposition of the great arteries','Atrial septal defect','Patent ductus arteriosus','Coarctation of the aorta','Ventricular septal defect'], 'A', 'Transposition causes parallel circulations and profound cyanosis soon after birth. A narrow mediastinum can produce the classic “egg-on-a-string” appearance.'), ('C', 'A 6-year-old with asthma has cough and wheeze twice weekly but has had one exacerbation requiring oral corticosteroids in the past year. Which long-term goal is most appropriate?', ['Treat only when symptoms are severe','Reduce symptom burden and future exacerbation risk','Avoid all inhaled medications because of adverse effects','Accept school absence as unavoidable','Use chronic oral corticosteroids'], 'B', 'Asthma management targets both current symptom control and reduction of future risks, including severe exacerbations and medication adverse effects.'), ('C', 'An 11-year-old with asthma has increasing symptoms despite medium-dose inhaled corticosteroid therapy. Before escalating treatment, which feature most strongly suggests an alternative diagnosis?', ['Symptoms only after viral infections','Inspiratory stridor localized to the neck during exercise','Improvement with bronchodilator','Personal history of eczema','Family history of atopy'], 'B', 'Inspiratory, upper-airway noise during exercise suggests inducible laryngeal obstruction rather than lower-airway bronchospasm.'), ('C', 'A 13-year-old is treated for severe asthma with repeated albuterol. She develops tremor, tachycardia, and a low serum potassium concentration. Which mechanism best explains the hypokalemia?', ['Increased gastrointestinal potassium loss','Intracellular shift of potassium due to beta2-adrenergic stimulation','Reduced aldosterone secretion','Hemolysis during phlebotomy','Renal tubular acidosis'], 'B', 'Beta2-agonists stimulate cellular potassium uptake, causing a temporary decrease in serum potassium.'), ('C', 'A 15-year-old with asthma reports daily symptoms and frequent nighttime awakenings. He uses his inhaled corticosteroid correctly and consistently, avoids tobacco smoke, and has no alternate diagnosis. What is the most appropriate next principle?', ['Step up controller therapy and reassess response','Discontinue all maintenance therapy','Use a long-acting beta2-agonist alone','Use antibiotics for chronic airway inflammation','Rely on chest radiography to guide treatment'], 'A', 'After confirming diagnosis, adherence, technique, and modifiable factors, persistent uncontrolled asthma warrants a step-up in ICS-containing controller treatment.'), ('C', 'A child with acute asthma initially has diffuse wheezing. Thirty minutes later, wheezing is no longer audible, but the child is drowsy and has shallow respirations. What is the best interpretation?', ['Improvement after bronchodilator therapy','Life-threatening fatigue and markedly reduced airflow','Anxiety-related hyperventilation','Normal sleep after treatment','Isolated upper airway obstruction'], 'B', 'Loss of wheeze with worsening mental status and shallow breathing indicates minimal airflow and impending respiratory failure.'), ('C', 'A 9-year-old’s spirometry shows FEV1 65% predicted, FVC 90% predicted, and FEV1/FVC 0.62. After albuterol, FEV1 improves by 16%. Which conclusion is best?', ['Restrictive disease without reversibility','Obstructive ventilatory defect with significant bronchodilator responsiveness','Normal lung function','Fixed upper-airway obstruction','Isolated diffusion defect'], 'B', 'Low FEV1/FVC indicates obstruction. A post-bronchodilator FEV1 increase of at least 12% supports variable airflow limitation.'), ('C', 'A 7-year-old with recurrent wheeze is prescribed an inhaled corticosteroid. The parent worries this medication is “only for attacks.” Which explanation is most accurate?', ['It provides immediate rescue bronchodilation','It reduces airway inflammation and lowers the risk of future symptoms and exacerbations','It should be used only during bacterial infections','It permanently cures asthma after one course','It is intended solely to suppress cough'], 'B', 'Inhaled corticosteroids are controller medications. They reduce airway inflammation and future exacerbation risk but do not provide the immediate relief of a reliever bronchodilator.'), ('C', 'A 10-year-old with poorly controlled asthma is admitted twice in 6 months. At discharge, which intervention is most likely to reduce repeat exacerbations?', ['A written asthma action plan, inhaler teaching, trigger review, and arranged follow-up','A chest radiograph every 2 weeks','Routine prophylactic oral antibiotics','Stopping physical education permanently','Providing a reliever inhaler without instructions'], 'A', 'Discharge planning should include education, written action plan, inhaler technique review, trigger modification, appropriate controller treatment, and timely follow-up.') ] assert len(questions)==50 doc=Document() sec=doc.sections[0]; sec.top_margin=Inches(.7); sec.bottom_margin=Inches(.7); sec.left_margin=Inches(.75); sec.right_margin=Inches(.75) styles=doc.styles styles['Normal'].font.name='Arial'; styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),'Arial'); styles['Normal'].font.size=Pt(10) styles['Normal'].paragraph_format.space_after=Pt(4) for style_name,size,color in [('Title',18,'1F4E79'),('Heading 1',14,'1F4E79'),('Heading 2',12,'1F4E79')]: s=styles[style_name]; s.font.name='Arial'; s.font.size=Pt(size); s.font.bold=True; s.font.color.rgb=__import__('docx').shared.RGBColor.from_string(color) # Header/footer h=sec.header.paragraphs[0]; h.text='USMLE-STYLE PRACTICE EXAM | NEONATOLOGY, NEWBORN EXAMINATION & ASTHMA'; h.alignment=WD_ALIGN_PARAGRAPH.CENTER; h.runs[0].font.size=Pt(8); h.runs[0].font.bold=True f=sec.footer.paragraphs[0]; f.alignment=WD_ALIGN_PARAGRAPH.CENTER; r=f.add_run('Page '); begin=OxmlElement('w:fldChar'); begin.set(qn('w:fldCharType'),'begin'); instr=OxmlElement('w:instrText'); instr.set(qn('xml:space'),'preserve'); instr.text='PAGE'; end=OxmlElement('w:fldChar'); end.set(qn('w:fldCharType'),'end'); r._r.extend([begin,instr,end]) def add_opts(opts): for i,opt in enumerate(opts): p=doc.add_paragraph(style='Normal'); p.paragraph_format.left_indent=Inches(.22); p.paragraph_format.first_line_indent=Inches(-.18); p.add_run(f'{chr(65+i)}. ').bold=True; p.add_run(opt) def qadd(n,q): p=doc.add_paragraph(); p.paragraph_format.space_before=Pt(7); p.paragraph_format.keep_with_next=True; r=p.add_run(f'{n}. '); r.bold=True; p.add_run(q[1]); add_opts(q[2]) doc.add_heading('USMLE-Style Multiple-Choice Examination',0) p=doc.add_paragraph('Topics: Neonatology Introduction, Examination of the Newborn, and Asthma') p.alignment=WD_ALIGN_PARAGRAPH.CENTER; p.runs[0].italic=True p=doc.add_paragraph('Total questions: 50 Time allowed: 90 minutes Single best answer') p.alignment=WD_ALIGN_PARAGRAPH.CENTER t=doc.add_table(rows=2, cols=2); t.style='Table Grid'; t.cell(0,0).text='Candidate name:'; t.cell(0,1).text=''; t.cell(1,0).text='Date:'; t.cell(1,1).text='' doc.add_heading('Instructions',1) doc.add_paragraph('Select the ONE best answer for each question. Section A assesses core concepts. Sections B and C consist entirely of clinical scenarios, with Section C emphasizing diagnostic reasoning and management. The questions are educational practice items based on the uploaded lecture topics and aligned with standard clinical principles.') sections=[('SECTION A: Core Knowledge', range(0,20), '20 questions'),('SECTION B: Clinical Scenarios', range(20,35), '15 questions'),('SECTION C: Advanced Clinical Scenarios and Management', range(35,50), '15 questions')] for title, inds, subtitle in sections: doc.add_page_break(); doc.add_heading(title,1); doc.add_paragraph(subtitle) for idx in inds: qadd(idx+1,questions[idx]) doc.add_page_break(); doc.add_heading('Answer Key and Explanations',0) doc.add_paragraph('For instructor use or self-assessment. The correct answer is followed by a concise rationale.') for title, inds, _ in sections: doc.add_heading(title,1) for idx in inds: q=questions[idx] p=doc.add_paragraph(); p.paragraph_format.space_before=Pt(5); p.paragraph_format.keep_together=True r=p.add_run(f'{idx+1}. {q[3]}. '); r.bold=True p.add_run(q[4]) doc.add_heading('Content Note',1) doc.add_paragraph('The source asthma lecture includes older terminology and broad management statements. This examination uses current clinical principles, including assessment of inhaler technique and adherence before stepping up treatment, and inhaled corticosteroid-containing therapy for persistent asthma. The lecture files “NEONATOLOGY INTRO” and “EXAMINATION OF THE NEW BORN” were image-based, so their titles and the requested subject areas were used to frame the neonatal content.') doc.save(out) print(out) PY python3 - <<'PY' from docx import Document p='/tmp/workspace/usmle-mcq-exam/output/Neonatology_Newborn_Examination_Asthma_USMLE_MCQ_Exam.docx' d=Document(p) text='\n'.join(x.text for x in d.paragraphs) print('File:',p) print('Question occurrences:',sum(1 for i in range(1,51) if f'{i}. ' in text)) print('Sections:', [x in text for x in ['SECTION A: Core Knowledge','SECTION B: Clinical Scenarios','SECTION C: Advanced Clinical Scenarios and Management','Answer Key and Explanations']]) print('Paragraph count:',len(d.paragraphs)) PY
Neonatology Newborn Examination Asthma USMLE MCQ Exam
Word Document · DOCX
SECTION A SHOULD BE 50 MCQS AND ANOTHER 10 SHOULD HAVE 6 SHORT CASES AND 4 LONG CASES THEN REMOVE THE MARKING KEY
~/
python3 - <<'PY' from docx import Document p='/tmp/workspace/usmle-mcq-exam/output/Neonatology_Newborn_Examination_Asthma_USMLE_MCQ_Exam.docx' d=Document(p) for i,x in enumerate(d.paragraphs[:18]): print(i,repr(x.text)) print('last index', next(i for i,x in enumerate(d.paragraphs) if x.text=='Answer Key and Explanations')) PY
python3 - <<'PY' from docx import Document from docx.shared import Inches, Pt, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml import OxmlElement from docx.oxml.ns import qn from pathlib import Path src='/tmp/workspace/usmle-mcq-exam/output/Neonatology_Newborn_Examination_Asthma_USMLE_MCQ_Exam.docx' out=Path('/tmp/workspace/usmle-mcq-exam/output/Neonatology_Newborn_Examination_Asthma_USMLE_MCQ_Exam_Revised_No_Marking_Key.docx') old=Document(src) # Extract original question blocks, excluding answer key ps=[p.text.strip() for p in old.paragraphs] stop=ps.index('Answer Key and Explanations') questions=[]; i=0 while i<stop: t=ps[i] if t and t[0].isdigit() and '. ' in t and t.split('. ',1)[0].isdigit(): n=int(t.split('. ',1)[0]); body=t.split('. ',1)[1] opts=[]; j=i+1 while j<stop and len(opts)<5: s=ps[j] if len(s)>2 and s[0] in 'ABCDE' and s[1:3]=='. ': opts.append(s) j+=1 if len(opts)==5: questions.append((n,body,opts)); i=j; continue i+=1 assert len(questions)==50, len(questions) cases_short=[ ('Short Case 1', 'A 3-day-old term newborn has visible jaundice. The infant is feeding adequately, has normal tone and temperature, and passed meconium within 24 hours. The mother is blood group O positive and the infant is A positive. Total serum bilirubin is 15 mg/dL.', ['State the most likely broad type of jaundice and give one important cause to evaluate in this infant.', 'List three clinical or laboratory findings that would make this jaundice pathologic rather than physiologic.', 'Outline the immediate assessment and initial management priorities.']), ('Short Case 2', 'A 1-hour-old newborn develops tachypnea (72/min), grunting, nasal flaring, and subcostal recession after an uncomplicated term vaginal delivery. Oxygen saturation is 89% on room air.', ['Name four differential diagnoses for neonatal respiratory distress in this setting.', 'List four immediate bedside assessments or interventions.', 'State two features that would indicate need for urgent escalation of respiratory support.']), ('Short Case 3', 'A 7-day-old infant presents with poor feeding, lethargy, reduced activity, and a temperature of 35.5°C. Capillary refill is 4 seconds. The infant had prolonged rupture of membranes before birth.', ['What is the most likely working diagnosis?', 'List four investigations to obtain promptly.', 'State the initial treatment approach while awaiting results.']), ('Short Case 4', 'A 4-year-old has recurrent wheeze and cough with viral illnesses and after exposure to dust. Symptoms improve after inhaled salbutamol. Between episodes, physical examination is normal.', ['Give three features supporting asthma in this child.', 'Give three alternative diagnoses that should be considered if the presentation is atypical.', 'State two factors to assess before escalating long-term asthma treatment.']), ('Short Case 5', 'An 8-year-old with known asthma presents with cough, wheeze, accessory muscle use, and oxygen saturation of 91% on room air. He is able to speak only in short phrases.', ['Classify the clinical severity broadly and justify your answer with two features.', 'List four elements of immediate management.', 'Name three findings that would indicate a life-threatening exacerbation.']), ('Short Case 6', 'During newborn examination, a 2-day-old girl has asymmetric thigh folds and a palpable “clunk” when the hip is abducted and lifted anteriorly.', ['Name the most likely diagnosis and the maneuver producing the clunk.', 'State two risk factors for this condition.', 'Describe the appropriate next step in evaluation or referral.']) ] long_cases=[ ('Long Case 1: Neonatal Sepsis', 'A male infant is born at 38 weeks after 22 hours of ruptured membranes. The mother developed intrapartum fever and received incomplete antibiotic prophylaxis. At 10 hours of life, the infant has poor feeding, grunting, tachypnea, mottled skin, temperature instability, and delayed capillary refill. Blood glucose is 48 mg/dL.', ['Identify the most likely diagnosis and explain why this infant is high risk.', 'Describe your immediate stabilization priorities using an ABC approach.', 'List the investigations you would obtain before or at the time antibiotics are started.', 'Outline empiric antimicrobial management and explain why treatment must not wait for culture results.', 'State four complications or clinical changes that should be monitored closely.']), ('Long Case 2: Newborn Examination and Congenital Heart Disease', 'A 30-hour-old term newborn has progressive cyanosis and tachypnea. Pulse oximetry is 78% in the right hand and 88% in a foot. The infant has a single loud S2 and no significant murmur. Supplemental oxygen produces little improvement. Chest radiography demonstrates a narrow superior mediastinum.', ['Interpret the preductal and postductal saturation pattern and identify the most likely cardiac diagnosis.', 'Explain the underlying circulatory abnormality and why mixing of blood is necessary for survival.', 'List the immediate stabilization and definitive management principles.', 'Give three alternative causes of cyanosis in a newborn and one clue that distinguishes each from congenital heart disease.', 'Describe the role of a complete newborn physical examination and pulse oximetry screening in detecting critical congenital heart disease.']), ('Long Case 3: Acute Severe Asthma', 'A 12-year-old with asthma is brought to the emergency department after 2 days of worsening cough and breathlessness following a viral upper respiratory infection. He has used his reliever inhaler repeatedly with little benefit. He is anxious, sitting upright, speaking single words, respiratory rate is 36/min, pulse 132/min, and oxygen saturation is 87% on room air. Air entry is markedly reduced bilaterally.', ['Assess the severity of this exacerbation and identify the features that make it life-threatening.', 'Provide a stepwise immediate management plan, including monitoring and reassessment.', 'Explain why reduced wheeze in this setting is not reassuring.', 'List four possible precipitating or contributing factors to review after stabilization.', 'Give a discharge and follow-up plan if the patient improves sufficiently for discharge.']), ('Long Case 4: Chronic Asthma Control', 'A 10-year-old has asthma symptoms on most days, wakes from cough three nights per week, and missed school twice this month. She uses salbutamol daily. An inhaled corticosteroid was prescribed 6 months ago, but her parent says it is used “only when she is bad.” Examination today is normal. The family keeps windows open during seasonal pollen peaks and a household member smokes indoors.', ['Assess the level of asthma control and identify the major risk factors for future exacerbations.', 'Describe how you would check and improve medication use before changing treatment.', 'Outline a long-term management plan including pharmacologic and nonpharmacologic components.', 'Provide key education points for a written asthma action plan.', 'State the follow-up goals used to judge whether management is working.']) ] D=Document(); sec=D.sections[0]; sec.top_margin=Inches(.7); sec.bottom_margin=Inches(.7); sec.left_margin=Inches(.78); sec.right_margin=Inches(.78) normal=D.styles['Normal']; normal.font.name='Arial'; normal._element.rPr.rFonts.set(qn('w:eastAsia'),'Arial'); normal.font.size=Pt(10); normal.paragraph_format.space_after=Pt(4) for st,size in [('Title',18),('Heading 1',14),('Heading 2',12)]: s=D.styles[st]; s.font.name='Arial'; s.font.size=Pt(size); s.font.bold=True; s.font.color.rgb=RGBColor(31,78,121) h=sec.header.paragraphs[0]; h.text='EXAMINATION | NEONATOLOGY, NEWBORN EXAMINATION & ASTHMA'; h.alignment=WD_ALIGN_PARAGRAPH.CENTER; h.runs[0].font.size=Pt(8); h.runs[0].font.bold=True f=sec.footer.paragraphs[0]; f.alignment=WD_ALIGN_PARAGRAPH.CENTER; r=f.add_run('Page '); a=OxmlElement('w:fldChar'); a.set(qn('w:fldCharType'),'begin'); b=OxmlElement('w:instrText'); b.set(qn('xml:space'),'preserve'); b.text='PAGE'; c=OxmlElement('w:fldChar'); c.set(qn('w:fldCharType'),'end'); r._r.extend([a,b,c]) D.add_heading('Examination: Neonatology, Newborn Examination and Asthma',0) p=D.add_paragraph('Candidate Name: _______________________________________ Date: ___________________'); p.paragraph_format.space_after=Pt(12) D.add_heading('Instructions',1) D.add_paragraph('This paper has two sections. Section A contains 50 single-best-answer multiple-choice questions. Section B contains 10 clinical cases: 6 short cases and 4 long cases. Answer all questions. No marking key is included in this candidate paper.') D.add_page_break(); D.add_heading('SECTION A: Multiple-Choice Questions',1); D.add_paragraph('50 questions. Select ONE best answer for each question.') for n,q,opts in questions: p=D.add_paragraph(); p.paragraph_format.space_before=Pt(6); p.paragraph_format.keep_with_next=True; rr=p.add_run(f'{n}. '); rr.bold=True; p.add_run(q) for opt in opts: p=D.add_paragraph(opt); p.paragraph_format.left_indent=Inches(.25); p.paragraph_format.first_line_indent=Inches(-.18); p.paragraph_format.space_after=Pt(1) D.add_page_break(); D.add_heading('SECTION B: Clinical Cases',1); D.add_paragraph('10 cases: 6 short cases and 4 long cases. Answer all parts clearly and concisely.') D.add_heading('Part I: Short Cases',2) for title,stem,subs in cases_short: D.add_heading(title,2); D.add_paragraph(stem) for j,s in enumerate(subs,1): D.add_paragraph(f'{chr(96+j)}. {s}') D.add_paragraph('________________________________________________________________________________') D.add_paragraph('________________________________________________________________________________') D.add_page_break(); D.add_heading('Part II: Long Cases',2) for title,stem,subs in long_cases: D.add_heading(title,2); D.add_paragraph(stem) for j,s in enumerate(subs,1): D.add_paragraph(f'{chr(96+j)}. {s}') D.add_paragraph('________________________________________________________________________________') D.add_paragraph('________________________________________________________________________________') D.add_paragraph('________________________________________________________________________________') D.add_heading('End of Examination',1) D.save(out) print(out) PY python3 - <<'PY' from docx import Document p='/tmp/workspace/usmle-mcq-exam/output/Neonatology_Newborn_Examination_Asthma_USMLE_MCQ_Exam_Revised_No_Marking_Key.docx' d=Document(p); text='\n'.join(x.text for x in d.paragraphs) print('exists',__import__('os').path.exists(p),'Q50', '50. ' in text, 'short', text.count('Short Case'), 'long', text.count('Long Case'), 'key?', 'Answer Key' in text or 'Correct answer' in text, 'paras',len(d.paragraphs)) PY
Neonatology Newborn Examination Asthma USMLE MCQ Exam Revised No Marking Key
Word Document · DOCX
CHANGE IT TO PDF
~/
~/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09
python3 - <<'PY' from docx import Document p='/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/MID TERM PEADS.docx' d=Document(p) print('paragraphs',len(d.paragraphs),'tables',len(d.tables),'inline_shapes',len(d.inline_shapes),'sections',len(d.sections)) for i,x in enumerate(d.paragraphs): if x.text.strip(): print(f'{i}: [{x.style.name}] {x.text[:500]}') for ti,t in enumerate(d.tables): print('TABLE',ti,'rows',len(t.rows),'cols',len(t.columns)) for row in t.rows[:3]: print(' | '.join(c.text.replace('\n',' / ') for c in row.cells)) PY
mkdir -p "/tmp/workspace/mid-term-peads-pdf/output" && python3 - <<'PY' from docx import Document from reportlab.lib import colors from reportlab.lib.enums import TA_CENTER, TA_LEFT from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import cm from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, KeepTogether from reportlab.pdfbase.pdfmetrics import stringWidth from xml.sax.saxutils import escape from pathlib import Path source=Path('/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/MID TERM PEADS.docx') out=Path('/tmp/workspace/mid-term-peads-pdf/output/MID_TERM_PEADS.pdf') docx=Document(source) styles=getSampleStyleSheet() styles.add(ParagraphStyle('ExamTitle', parent=styles['Title'], fontName='Helvetica-Bold', fontSize=16, leading=20, alignment=TA_CENTER, textColor=colors.HexColor('#1F4E79'), spaceAfter=10)) styles.add(ParagraphStyle('H1Exam', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=13, leading=16, textColor=colors.HexColor('#1F4E79'), spaceBefore=10, spaceAfter=6, keepWithNext=True)) styles.add(ParagraphStyle('H2Exam', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=11, leading=14, textColor=colors.HexColor('#1F4E79'), spaceBefore=8, spaceAfter=4, keepWithNext=True)) styles.add(ParagraphStyle('BodyExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=9.2, leading=12, spaceAfter=3)) styles.add(ParagraphStyle('QuestionExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=9.2, leading=12, spaceBefore=5, spaceAfter=2, keepWithNext=True)) styles.add(ParagraphStyle('OptionExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=9, leading=11, leftIndent=14, firstLineIndent=-10, spaceAfter=1)) styles.add(ParagraphStyle('LineExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=8.4, leading=10, textColor=colors.HexColor('#444444'), spaceAfter=0)) story=[] for p in docx.paragraphs: text=p.text.strip() if not text: # Original has intentional page breaks in empty paragraphs. Detect them. xml=p._p.xml if 'w:type="page"' in xml or '<w:br w:type="page"' in xml: story.append(PageBreak()) continue safe=escape(text).replace('\n','<br/>') style_name=p.style.name if p.style else 'Normal' if style_name=='Title': style='ExamTitle' elif style_name=='Heading 1': style='H1Exam' elif style_name=='Heading 2': style='H2Exam' elif text.startswith(tuple(str(i)+'. ' for i in range(1,51))): style='QuestionExam' elif len(text)>2 and text[0] in 'ABCDE' and text[1:3]=='. ': style='OptionExam' elif text.startswith('_'): style='LineExam' else: style='BodyExam' story.append(Paragraph(safe,styles[style])) # Header/footer def header_footer(canvas, doc): canvas.saveState() w,h=A4 canvas.setFont('Helvetica-Bold',7.5) canvas.setFillColor(colors.HexColor('#1F4E79')) canvas.drawCentredString(w/2,h-1.1*cm,'EXAMINATION | NEONATOLOGY, NEWBORN EXAMINATION & ASTHMA') canvas.setStrokeColor(colors.HexColor('#1F4E79')) canvas.line(1.5*cm,h-1.25*cm,w-1.5*cm,h-1.25*cm) canvas.setFont('Helvetica',8) canvas.setFillColor(colors.black) canvas.drawCentredString(w/2,0.8*cm,f'Page {doc.page}') canvas.restoreState() pdf=SimpleDocTemplate(str(out),pagesize=A4,rightMargin=1.55*cm,leftMargin=1.55*cm,topMargin=1.6*cm,bottomMargin=1.25*cm,title='MID TERM PEADS') pdf.build(story,onFirstPage=header_footer,onLaterPages=header_footer) print(out) PY python3 - <<'PY' from pypdf import PdfReader p='/tmp/workspace/mid-term-peads-pdf/output/MID_TERM_PEADS.pdf' r=PdfReader(p) text='\n'.join(page.extract_text() or '' for page in r.pages) print('pages:',len(r.pages),'bytes:',__import__('os').path.getsize(p)) print('checks:', all(s in text for s in ['SECTION A: Multiple-Choice Questions','SECTION B: Clinical Cases','Short Case 6','Long Case 4: Chronic Asthma Control','End of Examination'])) print('answer key present:', 'Answer Key' in text) PY
MID TERM PEADS
PDF Document · PDF
MAKE A SIMILAR TEST FOR INTERNAL MEDICINE USING THE ATTACHED TOPICS INCLUDING SECOND AND THIRD LINE TREATMENT FOR TB
~/
tuberculosis drug resistant treatment
WHO consolidated guidelines tuberculosis module 4 treatment drug resistant tuberculosis 2025 second line medicines
~/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09
mkdir -p "/tmp/workspace/internal-medicine-tb-sarcoidosis/source" "/tmp/workspace/internal-medicine-tb-sarcoidosis/output" && python3 - <<'PY' from pptx import Presentation from pathlib import Path files=['/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/TUBERCULOSIS.pptx','/tmp/workspace/attachments/5fce3fd6-7010-4b78-8fb2-d11516b0cf09/Sarcoidosis_Registrar_Teaching (1) (2).pptx'] outdir=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/source') for f in files: prs=Presentation(f); out=outdir/(Path(f).stem+'.txt') with out.open('w',encoding='utf-8') as h: h.write(f'TITLE: {Path(f).name}\nSLIDES: {len(prs.slides)}\n\n') for i,sl in enumerate(prs.slides,1): tx=[] for sh in sl.shapes: if getattr(sh,'has_text_frame',False) and sh.text_frame.text.strip(): tx.append(sh.text_frame.text.strip()) if getattr(sh,'has_table',False): for row in sh.table.rows: tx.append(' | '.join(c.text.strip() for c in row.cells)) h.write(f'--- Slide {i} ---\n'+'\n'.join(tx)+'\n\n') print(Path(f).name,len(prs.slides),out) PY
https://www.who.int/teams/global-programme-on-tuberculosis-a…
python3 - <<'PY' from docx import Document from docx.shared import Inches, Pt, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml import OxmlElement from docx.oxml.ns import qn from pathlib import Path base=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis') out=base/'output/Internal_Medicine_Tuberculosis_Sarcoidosis_Examination.docx' Q=[ ('Tuberculosis is transmitted primarily by:', ['Fomites containing dried sputum','Inhalation of airborne droplet nuclei','Ingestion of contaminated milk only','Skin contact with an infected patient','Tick bite'], 'B'), ('The initial host response that contains Mycobacterium tuberculosis is mediated mainly by:', ['Neutrophil degranulation','CD4+ T-cell activation of macrophages','IgE-mediated mast-cell activation','Complement-mediated lysis','CD8+ T-cell destruction of alveolar epithelium'], 'B'), ('A positive tuberculin skin test or IGRA indicates:', ['Active pulmonary TB only','Exposure or infection with M tuberculosis but cannot alone distinguish active from latent disease','Drug resistance','Cure after TB treatment','Infectiousness'], 'B'), ('Which finding most strongly supports active pulmonary TB?', ['Positive IGRA with no symptoms','Upper-lobe cavitation plus positive sputum molecular test','Calcified granuloma only','History of BCG vaccination','Normal chest radiograph'], 'B'), ('The standard first-line drugs for drug-susceptible TB include:', ['Isoniazid, rifampicin, pyrazinamide, ethambutol','Bedaquiline, linezolid, clofazimine, delamanid','Streptomycin, amikacin, levofloxacin, ethionamide','Rifampicin, acyclovir, pyrazinamide, ethambutol','Isoniazid, vancomycin, pyrazinamide, ethambutol'], 'A'), ('Which first-line TB drug is most associated with optic neuritis and red-green color discrimination impairment?', ['Isoniazid','Rifampicin','Pyrazinamide','Ethambutol','Streptomycin'], 'D'), ('Pyridoxine supplementation is especially used with isoniazid to reduce the risk of:', ['Optic neuritis','Peripheral neuropathy','Hyperuricemia','Ototoxicity','QT prolongation'], 'B'), ('Rifampicin commonly causes:', ['Orange discoloration of body fluids and potent enzyme induction','Irreversible hearing loss','Hyperkalemia','Red-green color blindness','Aplastic anemia in most patients'], 'A'), ('Pyrazinamide commonly increases the risk of:', ['Hyperuricemia','Optic neuritis','Peripheral neuropathy','Tendon rupture','Hypothyroidism'], 'A'), ('MDR-TB is tuberculosis resistant at minimum to:', ['Isoniazid only','Rifampicin only','Isoniazid and rifampicin','Any fluoroquinolone','All first-line drugs'], 'C'), ('Rifampicin-resistant TB should prompt:', ['Assumption that treatment is complete','Rapid drug-susceptibility testing and specialized DR-TB regimen selection','Isoniazid monotherapy','Stopping all TB therapy','Routine treatment without further evaluation'], 'B'), ('Which is a key principle of treating drug-resistant TB?', ['Use a single active drug to minimize toxicity','Use an effective all-oral combination guided by drug-susceptibility testing','Avoid monitoring adverse effects','Use injectable agents in every patient','Continue an ineffective regimen until culture converts'], 'B'), ('Which drug is a core all-oral medicine used in contemporary DR-TB regimens and requires ECG/QT monitoring?', ['Bedaquiline','Amoxicillin','Isoniazid','Pyridoxine','Streptomycin'], 'A'), ('Linezolid toxicity that should be monitored during prolonged use includes:', ['Myelosuppression and peripheral neuropathy','Optic neuritis only from red-green color loss','Nephrolithiasis','Hyperthyroidism','Tendon rupture'], 'A'), ('A patient receiving a fluoroquinolone-containing DR-TB regimen should be counselled about risk of:', ['Tendon injury and QT prolongation','Orange urine only','Optic neuritis only','Hypercalcemia','Pancreatitis as the expected toxicity'], 'A'), ('Which medicine is classified as a second-line anti-TB agent and is a fluoroquinolone?', ['Levofloxacin','Rifampicin','Isoniazid','Pyrazinamide','Ethambutol'], 'A'), ('Which medicine is a second-line anti-TB agent that may cause psychosis or depression?', ['Cycloserine','Ethambutol','Rifampicin','Isoniazid','Amoxicillin'], 'A'), ('An injectable aminoglycoside historically used in some DR-TB regimens has a major risk of:', ['Ototoxicity and nephrotoxicity','Optic neuritis','Hyperuricemia','Severe enzyme induction','Orange tears'], 'A'), ('A molecular assay that detects M tuberculosis and rifampicin resistance is particularly useful because it:', ['Proves treatment completion','Rapidly identifies TB and a critical resistance marker','Replaces all culture and DST in every circumstance','Distinguishes latent from active TB alone','Measures adherence'], 'B'), ('The most important public-health intervention for a patient with infectious pulmonary TB is:', ['Isolation precautions, effective treatment, and contact evaluation','Routine corticosteroids','Avoiding all vaccines','Annual CT scanning for all contacts','Isoniazid monotherapy for the index case'], 'A'), ('Sarcoidosis is best described as:', ['A single-organ bacterial infection','A multisystem disorder characterized by noncaseating granulomas after exclusion of alternatives','A disease diagnosed by serum ACE alone','A malignancy of lymphocytes','An inherited deficiency of alpha-1 antitrypsin'], 'B'), ('The most common intrathoracic radiographic finding in sarcoidosis is:', ['Bilateral hilar lymphadenopathy','Unilateral pleural effusion','Apical cavitation in all patients','Miliary nodules only','Pneumothorax'], 'A'), ('The characteristic histopathologic lesion of sarcoidosis is:', ['Caseating granuloma with acid-fast bacilli','Noncaseating granuloma','Suppurative abscess','Amyloid deposition','Necrotizing vasculitis'], 'B'), ('Before diagnosing sarcoidosis in a patient with granulomatous lung disease, an important alternative to exclude is:', ['Tuberculosis','Essential hypertension','Osteoarthritis','Iron deficiency','Migraine'], 'A'), ('Hypercalcemia in sarcoidosis is most directly related to:', ['Increased extrarenal conversion of vitamin D to active form by macrophages','Reduced parathyroid hormone secretion by the pituitary','Rifampicin induction','Renal loss of calcium','Excess calcitonin'], 'A'), ('Erythema nodosum, bilateral hilar lymphadenopathy, fever, and ankle arthritis suggest:', ['Lofgren syndrome','Goodpasture syndrome','Kartagener syndrome','Behcet syndrome','Felty syndrome'], 'A'), ('Which presentation of sarcoidosis requires urgent specialist assessment because of risk of sudden death?', ['Cardiac conduction symptoms or syncope','Asymptomatic bilateral hilar adenopathy','Mild fatigue only','Stable erythema nodosum','Isolated asymptomatic hypercalciuria'], 'A'), ('Which examination is appropriate at baseline in newly diagnosed sarcoidosis?', ['Eye assessment for ocular involvement','Only a urine dipstick','No examination beyond chest auscultation','Routine colonoscopy','Bone marrow biopsy in all patients'], 'A'), ('An elevated serum ACE level in suspected sarcoidosis is:', ['Diagnostic by itself','Supportive at most and neither sufficiently sensitive nor specific to establish diagnosis','Always normal in active disease','A measure of TB drug resistance','A reason to avoid biopsy'], 'B'), ('A bronchoalveolar lavage with an increased CD4/CD8 ratio is:', ['Diagnostic of sarcoidosis','Supportive but not diagnostic in the right clinical context','Proof of active TB','A contraindication to biopsy','Specific for fungal infection'], 'B'), ('Scadding stage I pulmonary sarcoidosis is:', ['Bilateral hilar lymphadenopathy without lung parenchymal infiltrates','Hilar lymphadenopathy with parenchymal infiltrates','Parenchymal infiltrates without hilar lymphadenopathy','Pulmonary fibrosis','Normal chest radiograph'], 'A'), ('Scadding stage IV pulmonary sarcoidosis is characterized by:', ['Pulmonary fibrosis','Isolated bilateral hilar lymphadenopathy','Normal chest radiograph','Only erythema nodosum','Pleural effusion only'], 'A'), ('A patient with sarcoidosis and asymptomatic stage I bilateral hilar lymphadenopathy is often managed initially with:', ['Observation and scheduled clinical monitoring','Immediate multi-agent TB therapy','Long-term antibiotics','Emergency thoracotomy','Chemotherapy'], 'A'), ('The usual first-line systemic treatment for organ-threatening sarcoidosis is:', ['Corticosteroids','Isoniazid','Bedaquiline','Warfarin','Insulin'], 'A'), ('A commonly used steroid-sparing agent in sarcoidosis is:', ['Methotrexate','Penicillin','Digoxin','Ethambutol','Pyridoxine'], 'A'), ('Which is a recognized cutaneous manifestation of sarcoidosis?', ['Lupus pernio','Herpes zoster only','Tinea versicolor only','Petechiae from thrombocytopenia only','Urticaria due to food allergy only'], 'A'), ('Heerfordt syndrome includes parotid enlargement, uveitis, fever, and:', ['Facial nerve palsy','Optic neuritis from ethambutol','Aortic dissection','Nephrotic syndrome','Hemoptysis'], 'A'), ('A patient with suspected neurosarcoidosis may present with:', ['Facial nerve palsy','Isolated mechanical back pain only','Acute appendicitis','Iron deficiency alone','Isolated hyperlipidemia'], 'A'), ('The most common cause of death in advanced pulmonary sarcoidosis is:', ['Progressive pulmonary fibrosis with respiratory failure','Acute bacterial tonsillitis','Appendicitis','Peptic ulcer disease','Cataract'], 'A'), ('Which finding favors TB rather than sarcoidosis in a patient with granulomatous lymphadenitis?', ['Positive mycobacterial culture from tissue','Bilateral hilar adenopathy','Noncaseating granulomas alone','Erythema nodosum','Hypercalcemia'], 'A'), ('Which drug interaction is especially important with rifampicin?', ['Reduced efficacy of many drugs through enzyme induction','Predictable increased effect of every anticoagulant','No interaction with antiretrovirals','Universal prevention of QT prolongation','Improved oral contraceptive effect'], 'A'), ('The purpose of directly observed therapy or other adherence support in TB care is primarily to:', ['Improve completion and reduce acquired resistance','Replace microbiologic testing','Avoid adverse-effect monitoring','Eliminate need for contact tracing','Treat latent infection only'], 'A'), ('A patient taking bedaquiline and clofazimine requires review of:', ['QT interval and interacting QT-prolonging medicines','Red-green color vision only','Serum amylase only','Bone mineral density only','Blood group'], 'A'), ('A patient on linezolid develops numb feet and falling hemoglobin. The most likely explanation is:', ['Linezolid toxicity','Rifampicin enzyme induction','Ethambutol optic neuritis','Physiologic anemia only','Sarcoid hypercalcemia'], 'A'), ('The selection of a second-line or third-line DR-TB regimen should be based chiefly on:', ['Drug-susceptibility results, prior treatment exposure, comorbidities, and national/WHO guidance','The patient’s favorite medication color','Chest radiograph alone','A single sputum smear only','Serum ACE concentration'], 'A'), ('Which statement about injectable agents in DR-TB is most accurate?', ['They are no longer routinely preferred when effective all-oral regimens are available because toxicity is substantial','They are mandatory in every DR-TB regimen','They never cause adverse effects','They are first-line therapy for latent TB','They substitute for DST'], 'A'), ('In a patient with sarcoidosis, an abnormal ECG or palpitations should prompt evaluation for:', ['Cardiac sarcoidosis','Latent TB only','Drug-induced hyperuricemia','Routine seasonal allergy','Peptic ulcer disease'], 'A'), ('Which is the best overall diagnostic framework for sarcoidosis?', ['Compatible presentation, granulomatous inflammation when tissue is needed, and exclusion of mimics','Elevated ACE level alone','Response to corticosteroids alone','Chest CT alone','Family history alone'], 'A'), ('A patient receiving corticosteroids for sarcoidosis develops fever and productive cough. The next step should include:', ['Assessment for infection, including TB when epidemiologically relevant','Automatic escalation of steroids without assessment','Assuming sarcoidosis flare in every case','Stopping all monitoring','Treating with isoniazid alone'], 'A'), ] assert len(Q)==50 short=[ ('Short Case 1', 'A 32-year-old man has 6 weeks of cough, weight loss, evening fevers, night sweats, and intermittent hemoptysis. Chest radiograph shows a right upper-lobe cavity.', ['List four investigations that establish TB diagnosis and guide drug-resistance assessment.', 'State the immediate infection-control and public-health measures.', 'Name the standard first-line anti-TB medicines and one important toxicity of each.']), ('Short Case 2', 'A sputum molecular assay in a patient with pulmonary TB detects rifampicin resistance.', ['Define rifampicin-resistant TB and MDR-TB.', 'List four principles for selecting a second-line/DR-TB regimen.', 'Name four all-oral medicines used in contemporary DR-TB regimens and one monitoring issue for any two.']), ('Short Case 3', 'A patient receiving isoniazid, rifampicin, pyrazinamide, and ethambutol develops nausea, jaundice, and dark urine after 3 weeks.', ['Identify the likely serious adverse effect.', 'Outline your immediate clinical and laboratory assessment.', 'State principles of TB drug interruption and reintroduction with specialist input.']), ('Short Case 4', 'A 38-year-old woman has dry cough, fatigue, bilateral hilar lymphadenopathy, and noncaseating granulomas on lymph node biopsy.', ['State the three pillars of diagnosing sarcoidosis.', 'List four important alternative diagnoses to exclude.', 'Name three baseline organ assessments needed after diagnosis.']), ('Short Case 5', 'A patient with sarcoidosis reports painful red nodules on both shins, bilateral ankle swelling, and fever.', ['Name this acute sarcoidosis syndrome.', 'List two supportive investigations or findings.', 'Describe initial management principles and prognosis.']), ('Short Case 6', 'A patient on a bedaquiline-containing DR-TB regimen has palpitations. ECG shows QTc prolongation.', ['Name three potential contributors to QT prolongation in this situation.', 'Outline immediate assessment and monitoring actions.', 'State why DR-TB treatment changes should be made with specialist or programme input.']) ] long=[ ('Long Case 1: Drug-Susceptible Pulmonary Tuberculosis', 'A 41-year-old man with newly diagnosed HIV infection presents with fever, weight loss, cough, and night sweats. Sputum NAAT confirms M tuberculosis without rifampicin resistance. He has no focal neurologic signs and baseline liver tests are normal.', ['Describe the initial clinical assessment, including evaluation for severity and extrapulmonary disease.', 'Outline first-line treatment principles, including adherence support and relevant preventive measures.', 'Describe baseline and follow-up monitoring for toxicity and treatment response.', 'Explain important considerations when coordinating TB treatment with antiretroviral therapy.', 'State the public-health actions required for contacts and infection control.']), ('Long Case 2: Rifampicin-Resistant / MDR-TB', 'A 29-year-old woman previously treated for pulmonary TB returns with chronic cough, weight loss, and a smear-positive sputum. Rapid molecular testing detects M tuberculosis with rifampicin resistance. She has no known exposure to newer TB drugs. ECG and baseline blood count are available.', ['Explain the immediate diagnostic and resistance-testing strategy, including why full DST is essential.', 'Define MDR-TB and explain the purpose of second-line and third-line medicines.', 'Outline principles for constructing an all-oral DR-TB regimen under national/WHO programme guidance. Include examples of Group A/core and additional agents.', 'Describe key adverse-effect and laboratory monitoring for bedaquiline, linezolid, fluoroquinolones, clofazimine, cycloserine, and injectable agents if used.', 'Explain infection control, adherence support, psychosocial support, and follow-up microbiologic monitoring.']), ('Long Case 3: Pulmonary Sarcoidosis', 'A 45-year-old woman has 4 months of dry cough, exertional dyspnea, fatigue, and bilateral hilar and mediastinal adenopathy on chest imaging. HRCT shows perilymphatic nodules. Transbronchial biopsy demonstrates noncaseating granulomas. She is HIV negative and has no current fever or weight loss.', ['Formulate the differential diagnosis and explain how to exclude infectious, occupational, and malignant mimics before confirming sarcoidosis.', 'Describe staging and baseline assessment for pulmonary and extrapulmonary organ involvement.', 'State when observation is appropriate and when systemic treatment is indicated.', 'Outline corticosteroid treatment principles and steroid-sparing options for chronic or relapsing disease.', 'Identify red flags that require urgent referral for cardiac, ocular, neurologic, or severe pulmonary involvement.']), ('Long Case 4: Multisystem Sarcoidosis', 'A 36-year-old woman with biopsy-confirmed sarcoidosis develops palpitations, presyncope, blurred vision, and new facial weakness. ECG shows first-degree AV block. Calcium is elevated. She is not receiving immunosuppression.', ['Identify the organ-threatening manifestations suggested by this presentation and explain why they are urgent.', 'Outline immediate investigations and the specialist team members required.', 'Describe acute and longer-term treatment principles, including management of hypercalcemia.', 'Explain how TB and other infections should be considered before immunosuppression in an endemic setting.', 'Provide a monitoring and follow-up plan for disease activity, treatment toxicity, and complications.']) ] D=Document(); sec=D.sections[0]; sec.top_margin=Inches(.7); sec.bottom_margin=Inches(.7); sec.left_margin=Inches(.78); sec.right_margin=Inches(.78) normal=D.styles['Normal']; normal.font.name='Arial'; normal._element.rPr.rFonts.set(qn('w:eastAsia'),'Arial'); normal.font.size=Pt(10); normal.paragraph_format.space_after=Pt(4) for sname,sz in [('Title',18),('Heading 1',14),('Heading 2',12)]: s=D.styles[sname]; s.font.name='Arial'; s.font.size=Pt(sz); s.font.bold=True; s.font.color.rgb=RGBColor(31,78,121) h=sec.header.paragraphs[0]; h.text='INTERNAL MEDICINE EXAMINATION | TUBERCULOSIS & SARCOIDOSIS'; h.alignment=WD_ALIGN_PARAGRAPH.CENTER; h.runs[0].font.size=Pt(8); h.runs[0].font.bold=True f=sec.footer.paragraphs[0]; f.alignment=WD_ALIGN_PARAGRAPH.CENTER; r=f.add_run('Page '); a=OxmlElement('w:fldChar'); a.set(qn('w:fldCharType'),'begin'); b=OxmlElement('w:instrText'); b.set(qn('xml:space'),'preserve'); b.text='PAGE'; c=OxmlElement('w:fldChar'); c.set(qn('w:fldCharType'),'end'); r._r.extend([a,b,c]) D.add_heading('Internal Medicine Examination',0); p=D.add_paragraph('Topics: Tuberculosis, Drug-Resistant TB, Second-Line and Third-Line Treatment Principles, and Sarcoidosis'); p.alignment=WD_ALIGN_PARAGRAPH.CENTER; p.runs[0].italic=True D.add_paragraph('Candidate Name: _______________________________________ Date: ___________________') D.add_heading('Instructions',1); D.add_paragraph('This candidate paper has two sections. Section A has 50 single-best-answer MCQs. Section B has 10 clinical cases: 6 short and 4 long. Answer all questions. Regimen selection for drug-resistant TB must follow current national TB programme and WHO guidance, susceptibility results, prior exposure, and patient factors. No marking key is included.') D.add_page_break(); D.add_heading('SECTION A: Multiple-Choice Questions',1); D.add_paragraph('50 questions. Select ONE best answer for each question.') for n,(stem,opts,ans) in enumerate(Q,1): p=D.add_paragraph(); p.paragraph_format.space_before=Pt(6); p.paragraph_format.keep_with_next=True; x=p.add_run(f'{n}. '); x.bold=True; p.add_run(stem) for i,opt in enumerate(opts): p=D.add_paragraph(f'{chr(65+i)}. {opt}'); p.paragraph_format.left_indent=Inches(.25); p.paragraph_format.first_line_indent=Inches(-.18); p.paragraph_format.space_after=Pt(1) D.add_page_break(); D.add_heading('SECTION B: Clinical Cases',1); D.add_paragraph('10 cases: 6 short cases and 4 long cases. Answer all parts clearly and concisely.') D.add_heading('Part I: Short Cases',2) for title,stem,items in short: D.add_heading(title,2); D.add_paragraph(stem) for i,item in enumerate(items): D.add_paragraph(f'{chr(97+i)}. {item}') D.add_paragraph('_'*96); D.add_paragraph('_'*96) D.add_page_break(); D.add_heading('Part II: Long Cases',2) for title,stem,items in long: D.add_heading(title,2); D.add_paragraph(stem) for i,item in enumerate(items): D.add_paragraph(f'{chr(97+i)}. {item}') D.add_paragraph('_'*96); D.add_paragraph('_'*96); D.add_paragraph('_'*96) D.add_heading('End of Examination',1) D.save(out); print(out) PY
python3 - <<'PY' from docx import Document from docx.shared import Inches, Pt, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml import OxmlElement from docx.oxml.ns import qn from pathlib import Path outdir=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output'); outdir.mkdir(parents=True,exist_ok=True) out=outdir/'Internal_Medicine_TB_Sarcoidosis_Examination.docx' # (stem, options) Q=[ ('The main route of transmission of pulmonary TB is:', ['Inhalation of airborne droplet nuclei','Fomite contact','Tick bite','Fecal-oral spread']), ('A positive IGRA result establishes:', ['M tuberculosis infection but not active disease alone','Active TB only','Drug susceptibility','Treatment cure']), ('The four standard first-line drugs for drug-susceptible TB are:', ['Isoniazid, rifampicin, pyrazinamide, ethambutol','Bedaquiline, linezolid, clofazimine, delamanid','Levofloxacin, amikacin, cycloserine, ethionamide','Rifampicin, vancomycin, pyrazinamide, acyclovir']), ('The first-line TB medicine associated with optic neuritis is:', ['Ethambutol','Isoniazid','Rifampicin','Pyrazinamide']), ('Pyridoxine is co-prescribed with isoniazid primarily to prevent:', ['Peripheral neuropathy','Optic neuritis','Hyperuricemia','QT prolongation']), ('Rifampicin is notable for:', ['Potent enzyme induction and orange body fluids','Red-green color blindness','Ototoxicity','Tendon rupture']), ('Pyrazinamide commonly causes:', ['Hyperuricemia','Optic neuritis','Peripheral neuropathy','Sinus bradycardia']), ('MDR-TB is resistance to at least:', ['Isoniazid and rifampicin','Rifampicin alone','A fluoroquinolone only','All anti-TB drugs']), ('Rapid identification of rifampicin resistance should lead to:', ['Full drug-susceptibility testing and DR-TB programme referral','Isoniazid monotherapy','No further testing','Immediate treatment cessation']), ('The key principle of DR-TB therapy is:', ['An effective all-oral combination guided by DST','One active drug only','No adverse-effect monitoring','Injectable agents for all patients']), ('A core second-line drug requiring QT monitoring is:', ['Bedaquiline','Pyridoxine','Isoniazid','Ethambutol']), ('A major toxicity of prolonged linezolid therapy is:', ['Myelosuppression and neuropathy','Hyperuricemia only','Orange urine','Optic neuritis only']), ('Levofloxacin in DR-TB treatment can cause:', ['Tendon injury and QT prolongation','Red-green color blindness','Hypercalcemia','Severe enzyme induction']), ('Cycloserine may cause:', ['Neuropsychiatric toxicity','Optic neuritis','Orange secretions','Hyperuricemia']), ('Aminoglycoside injectable agents have important risk of:', ['Ototoxicity and nephrotoxicity','Hepatitis only','Hypercalcemia','Peripheral edema only']), ('A nucleic-acid amplification test is valuable because it:', ['Rapidly detects TB and can identify rifampicin resistance','Diagnoses latent TB alone','Proves cure','Replaces all DST']), ('The most important infection-control measure for infectious pulmonary TB is:', ['Airborne precautions plus effective treatment','Routine corticosteroids','Avoiding all vaccines','Antibiotics for every contact']), ('Adherence support in TB care aims mainly to:', ['Improve completion and prevent acquired resistance','Replace microbiology','Prevent all toxicity','Avoid contact tracing']), ('Selection of DR-TB medicines should consider:', ['DST, prior exposure, comorbidities, interactions and national guidance','Chest radiograph alone','Patient preference only','Serum ACE alone']), ('Bedaquiline plus clofazimine warrants monitoring of:', ['QT interval and interacting medicines','Visual acuity only','Serum urate only','Bone density only']), ('Sarcoidosis is characterized by:', ['Multisystem noncaseating granulomatous inflammation','Single-organ bacterial infection','Lymphoma in every patient','IgE-mediated disease']), ('The classic chest radiograph finding in sarcoidosis is:', ['Bilateral hilar lymphadenopathy','Unilateral pleural effusion','Apical cavitation in all patients','Miliary nodules only']), ('The histologic hallmark of sarcoidosis is:', ['Noncaseating granulomas','Caseating granulomas with AFB','Suppurative abscesses','Amyloid deposition']), ('Before diagnosing sarcoidosis, a critical mimic to exclude is:', ['Tuberculosis','Hypertension','Osteoarthritis','Migraine']), ('Sarcoid hypercalcemia is caused by:', ['Macrophage-mediated activation of vitamin D','Reduced renal calcium loss','Excess calcitonin','Rifampicin induction']), ('Erythema nodosum, ankle arthritis and bilateral hilar adenopathy are typical of:', ['Lofgren syndrome','Goodpasture syndrome','Behcet syndrome','Felty syndrome']), ('Syncope or palpitations in sarcoidosis require urgent evaluation for:', ['Cardiac sarcoidosis','Latent TB only','Peptic ulcer disease','Iron deficiency']), ('A baseline assessment in sarcoidosis should include:', ['Eye examination','No systemic review','Routine colonoscopy','Bone marrow biopsy in all']), ('Serum ACE in sarcoidosis is:', ['Supportive but not diagnostic alone','Diagnostic alone','Always normal','A resistance marker']), ('An increased BAL CD4/CD8 ratio is:', ['Supportive but not diagnostic','Proof of active TB','Specific for fungal infection','A contraindication to biopsy']), ('Scadding stage I sarcoidosis shows:', ['Bilateral hilar lymphadenopathy without infiltrates','Fibrosis','Infiltrates without hilar nodes','Normal radiograph']), ('Scadding stage IV sarcoidosis indicates:', ['Pulmonary fibrosis','Isolated hilar adenopathy','Normal imaging','Pleural effusion only']), ('Asymptomatic stage I sarcoidosis is often initially managed with:', ['Observation and monitoring','Multi-agent TB therapy','Emergency surgery','Chemotherapy']), ('First-line systemic treatment for organ-threatening sarcoidosis is:', ['Corticosteroids','Bedaquiline','Isoniazid','Warfarin']), ('A common steroid-sparing agent for sarcoidosis is:', ['Methotrexate','Penicillin','Digoxin','Pyridoxine']), ('A characteristic chronic skin lesion in sarcoidosis is:', ['Lupus pernio','Tinea versicolor','Herpes zoster','Urticaria only']), ('Heerfordt syndrome includes parotid enlargement, uveitis, fever and:', ['Facial nerve palsy','Aortic dissection','Nephrotic syndrome','Hemoptysis']), ('A common neurologic manifestation of sarcoidosis is:', ['Facial nerve palsy','Appendicitis','Carpal fracture','Migraine only']), ('Advanced pulmonary sarcoidosis can cause death through:', ['Progressive pulmonary fibrosis and respiratory failure','Acute tonsillitis','Peptic ulcer','Cataract']), ('A tissue culture positive for M tuberculosis favors:', ['TB rather than sarcoidosis','Sarcoidosis','Lofgren syndrome','Drug toxicity']), ('Rifampicin interactions occur because it:', ['Induces hepatic enzymes','Inhibits all metabolism','Prevents QT prolongation','Causes hypercalcemia']), ('Linezolid-associated anemia and neuropathy require:', ['Blood-count and neurologic monitoring','No monitoring','Color vision testing only','Serum urate only']), ('Injectable agents in DR-TB are:', ['Not routinely preferred if effective all-oral options exist','Mandatory for every patient','First-line latent TB treatment','Substitutes for DST']), ('An abnormal ECG in sarcoidosis should raise suspicion for:', ['Cardiac involvement','Latent infection only','Hyperuricemia','Drug cure']), ('The best diagnostic framework for sarcoidosis is:', ['Compatible pattern, granulomas when needed, exclusion of mimics','ACE alone','Steroid response alone','CT alone']), ('Fever and productive cough in an immunosuppressed sarcoidosis patient should prompt:', ['Infection assessment, including TB where relevant','Automatic steroid escalation','No investigation','Isoniazid alone']), ('A WHO-described six-month all-oral DR-TB regimen includes bedaquiline, delamanid, linezolid, levofloxacin and:', ['Clofazimine','Ethambutol','Isoniazid','Streptomycin']), ('A DR-TB patient with prolonged QTc requires:', ['Review of QT-prolonging drugs and specialist-guided regimen adjustment','No change in monitoring','Stopping all treatment without review','Ethambutol monotherapy']), ('The appropriate care model for complex DR-TB is:', ['Specialist or national TB programme-supported management','Self-directed drug selection','Chest radiograph-only follow-up','No microbiologic monitoring']), ('An important reason to use multiple active TB drugs is to:', ['Prevent selection of resistant bacilli','Reduce all monitoring needs','Eliminate infection control','Avoid drug interactions']), ] assert len(Q)==50 short=[ ('Short Case 1','A 32-year-old man has 6 weeks of cough, weight loss, evening fever, night sweats and hemoptysis. Chest radiograph shows an upper-lobe cavity.',['List four investigations to confirm TB and assess drug resistance.','State immediate infection-control and public-health actions.','Name the first-line medicines and one important toxicity of each.']), ('Short Case 2','A molecular test detects M tuberculosis with rifampicin resistance.',['Define rifampicin-resistant TB and MDR-TB.','List four principles for selecting a DR-TB regimen.','Name four second-line/DR-TB medicines and two key monitoring requirements.']), ('Short Case 3','A patient receiving HRZE develops jaundice, nausea and dark urine after 3 weeks.',['Identify the likely serious adverse effect.','Outline immediate clinical and laboratory assessment.','State principles for treatment interruption and reintroduction with specialist support.']), ('Short Case 4','A 38-year-old woman has dry cough, bilateral hilar adenopathy and noncaseating granulomas on biopsy.',['State the three pillars for diagnosing sarcoidosis.','List four alternative diagnoses to exclude.','Name three baseline organ assessments.']), ('Short Case 5','A patient has tender red nodules on both shins, fever, ankle arthritis and bilateral hilar adenopathy.',['Name the syndrome.','List two supportive findings or investigations.','Describe initial management principles and prognosis.']), ('Short Case 6','A patient on bedaquiline-containing DR-TB treatment reports palpitations and has a prolonged QTc.',['Name three contributors to QT prolongation.','Outline immediate assessment and monitoring.','Explain why regimen changes require specialist/programme input.'])] long=[ ('Long Case 1: Drug-Susceptible Pulmonary TB','A 41-year-old man with newly diagnosed HIV has fever, weight loss, cough and night sweats. Sputum NAAT confirms M tuberculosis without rifampicin resistance.',['Describe initial clinical assessment, including severity and extrapulmonary disease.','Outline first-line treatment, adherence support and preventive measures.','Describe baseline and follow-up toxicity and response monitoring.','Explain TB and antiretroviral treatment coordination.','State infection-control and contact-management actions.']), ('Long Case 2: Rifampicin-Resistant / MDR-TB','A 29-year-old woman previously treated for pulmonary TB has smear-positive disease and rapid molecular testing shows rifampicin resistance.',['Explain the resistance-testing strategy and why full DST is essential.','Define MDR-TB and explain the role of second-line and third-line medicines.','Outline construction principles for an all-oral regimen under national/WHO guidance, with examples of core and additional drugs.','Describe adverse-effect monitoring for bedaquiline, linezolid, fluoroquinolones, clofazimine, cycloserine and injectables if used.','Explain infection control, adherence, psychosocial support and microbiologic follow-up.']), ('Long Case 3: Pulmonary Sarcoidosis','A 45-year-old woman has dry cough, exertional dyspnea, bilateral hilar and mediastinal adenopathy, and noncaseating granulomas on transbronchial biopsy.',['Formulate the differential diagnosis and exclusion of infectious, occupational and malignant mimics.','Describe staging and baseline pulmonary and extrapulmonary assessment.','State when observation is appropriate and when treatment is indicated.','Outline corticosteroid and steroid-sparing treatment principles.','Identify red flags for urgent cardiac, eye, neurologic or severe pulmonary referral.']), ('Long Case 4: Multisystem Sarcoidosis','A 36-year-old woman with biopsy-confirmed sarcoidosis develops palpitations, presyncope, blurred vision, facial weakness, first-degree AV block and hypercalcemia.',['Identify organ-threatening manifestations and explain urgency.','Outline immediate investigations and multidisciplinary referrals.','Describe acute and long-term treatment principles, including hypercalcemia.','Explain assessment for TB and other infections before immunosuppression in endemic settings.','Provide monitoring for disease activity, treatment toxicity and complications.'])] D=Document(); sec=D.sections[0]; sec.top_margin=Inches(.7); sec.bottom_margin=Inches(.7); sec.left_margin=Inches(.78); sec.right_margin=Inches(.78) D.styles['Normal'].font.name='Arial'; D.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),'Arial'); D.styles['Normal'].font.size=Pt(10); D.styles['Normal'].paragraph_format.space_after=Pt(4) for sn,sz in [('Title',18),('Heading 1',14),('Heading 2',12)]: D.styles[sn].font.name='Arial'; D.styles[sn].font.size=Pt(sz); D.styles[sn].font.bold=True; D.styles[sn].font.color.rgb=RGBColor(31,78,121) h=sec.header.paragraphs[0]; h.text='INTERNAL MEDICINE EXAMINATION | TUBERCULOSIS & SARCOIDOSIS'; h.alignment=WD_ALIGN_PARAGRAPH.CENTER; h.runs[0].font.size=Pt(8); h.runs[0].font.bold=True D.add_heading('Internal Medicine Examination',0); p=D.add_paragraph('Topics: Tuberculosis, Drug-Resistant TB, Second-Line and Third-Line Treatment Principles, and Sarcoidosis'); p.alignment=WD_ALIGN_PARAGRAPH.CENTER D.add_paragraph('Candidate Name: _______________________________________ Date: ___________________') D.add_heading('Instructions',1); D.add_paragraph('Section A contains 50 single-best-answer MCQs. Section B contains 10 clinical cases: 6 short cases and 4 long cases. Answer all questions. Drug-resistant TB regimens must follow current national TB programme/WHO guidance, DST, prior treatment and individual patient factors. No marking key is included.') D.add_page_break(); D.add_heading('SECTION A: Multiple-Choice Questions',1); D.add_paragraph('50 questions. Select ONE best answer.') for n,(stem,opts) in enumerate(Q,1): p=D.add_paragraph(); p.paragraph_format.space_before=Pt(6); p.paragraph_format.keep_with_next=True; p.add_run(f'{n}. ').bold=True; p.add_run(stem) for i,o in enumerate(opts): p=D.add_paragraph(f'{chr(65+i)}. {o}'); p.paragraph_format.left_indent=Inches(.25); p.paragraph_format.first_line_indent=Inches(-.18); p.paragraph_format.space_after=Pt(1) D.add_page_break(); D.add_heading('SECTION B: Clinical Cases',1); D.add_paragraph('10 cases: 6 short cases and 4 long cases. Answer all parts clearly and concisely.') D.add_heading('Part I: Short Cases',2) for title,stem,items in short: D.add_heading(title,2); D.add_paragraph(stem) for i,it in enumerate(items): D.add_paragraph(f'{chr(97+i)}. {it}'); D.add_paragraph('_'*95); D.add_paragraph('_'*95) D.add_page_break(); D.add_heading('Part II: Long Cases',2) for title,stem,items in long: D.add_heading(title,2); D.add_paragraph(stem) for i,it in enumerate(items): D.add_paragraph(f'{chr(97+i)}. {it}'); D.add_paragraph('_'*95); D.add_paragraph('_'*95); D.add_paragraph('_'*95) D.add_heading('End of Examination',1); D.save(out); print(out) PY python3 - <<'PY' from docx import Document p='/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.docx'; d=Document(p); t='\n'.join(x.text for x in d.paragraphs) print('questions',sum(f'{i}. ' in t for i in range(1,51)),'short',sum(f'Short Case {i}' in t for i in range(1,7)),'long',sum(f'Long Case {i}' in t for i in range(1,5)),'answer', 'Answer Key' in t) PY
python3 - <<'PY' from docx import Document from reportlab.lib import colors from reportlab.lib.enums import TA_CENTER from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import cm from reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak from xml.sax.saxutils import escape from pathlib import Path source=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.docx') out=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf') docx=Document(source) styles=getSampleStyleSheet() styles.add(ParagraphStyle('ExamTitle', parent=styles['Title'], fontName='Helvetica-Bold', fontSize=16, leading=20, alignment=TA_CENTER, textColor=colors.HexColor('#1F4E79'), spaceAfter=10)) styles.add(ParagraphStyle('H1Exam', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=13, leading=16, textColor=colors.HexColor('#1F4E79'), spaceBefore=10, spaceAfter=6, keepWithNext=True)) styles.add(ParagraphStyle('H2Exam', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=11, leading=14, textColor=colors.HexColor('#1F4E79'), spaceBefore=8, spaceAfter=4, keepWithNext=True)) styles.add(ParagraphStyle('BodyExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=9.2, leading=12, spaceAfter=3)) styles.add(ParagraphStyle('QuestionExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=9.2, leading=12, spaceBefore=5, spaceAfter=2, keepWithNext=True)) styles.add(ParagraphStyle('OptionExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=9, leading=11, leftIndent=14, firstLineIndent=-10, spaceAfter=1)) styles.add(ParagraphStyle('LineExam', parent=styles['BodyText'], fontName='Helvetica', fontSize=8.4, leading=10, textColor=colors.HexColor('#444444'), spaceAfter=0)) story=[] for p in docx.paragraphs: text=p.text.strip() if not text: if 'w:type="page"' in p._p.xml or '<w:br w:type="page"' in p._p.xml: story.append(PageBreak()) continue safe=escape(text).replace('\n','<br/>') sn=p.style.name if p.style else 'Normal' if sn=='Title': st='ExamTitle' elif sn=='Heading 1': st='H1Exam' elif sn=='Heading 2': st='H2Exam' elif text.startswith(tuple(str(i)+'. ' for i in range(1,51))): st='QuestionExam' elif len(text)>2 and text[0] in 'ABCD' and text[1:3]=='. ': st='OptionExam' elif text.startswith('_'): st='LineExam' else: st='BodyExam' story.append(Paragraph(safe,styles[st])) def header_footer(canvas,doc): canvas.saveState(); w,h=A4 canvas.setFont('Helvetica-Bold',7.5); canvas.setFillColor(colors.HexColor('#1F4E79')) canvas.drawCentredString(w/2,h-1.1*cm,'INTERNAL MEDICINE EXAMINATION | TUBERCULOSIS & SARCOIDOSIS') canvas.setStrokeColor(colors.HexColor('#1F4E79')); canvas.line(1.5*cm,h-1.25*cm,w-1.5*cm,h-1.25*cm) canvas.setFont('Helvetica',8); canvas.setFillColor(colors.black); canvas.drawCentredString(w/2,.8*cm,f'Page {doc.page}') canvas.restoreState() pdf=SimpleDocTemplate(str(out),pagesize=A4,leftMargin=1.55*cm,rightMargin=1.55*cm,topMargin=1.6*cm,bottomMargin=1.25*cm,title='Internal Medicine TB and Sarcoidosis Examination') pdf.build(story,onFirstPage=header_footer,onLaterPages=header_footer) print(out) PY python3 - <<'PY' from pypdf import PdfReader from pathlib import Path p=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf') r=PdfReader(str(p)); text='\n'.join(x.extract_text() or '' for x in r.pages) checks=['SECTION A: Multiple-Choice Questions','SECTION B: Clinical Cases','Short Case 6','Long Case 4: Multisystem Sarcoidosis','End of Examination','six-month all-oral DR-TB regimen'] print('exists',p.exists(),'pages',len(r.pages),'bytes',p.stat().st_size,'checks',[x in text for x in checks],'answerkey','Answer Key' in text) PY
~/internal-medicine-tb-sarcoidosis
~/
mkdir -p "/tmp/workspace/internal-medicine-tb-sarcoidosis/output" && python3 - <<'PY' from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle from reportlab.lib.enums import TA_CENTER from reportlab.lib import colors from reportlab.lib.units import cm from reportlab.platypus import SimpleDocTemplate,Paragraph,PageBreak from xml.sax.saxutils import escape from pathlib import Path out=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf') # 50 original single-best-answer questions qs=[ ('TB is transmitted mainly by:', ['Inhalation of airborne droplet nuclei','Fomite contact','Tick bite','Fecal-oral spread']), ('A positive IGRA establishes:', ['M tuberculosis infection but not active disease alone','Active TB only','Drug susceptibility','Treatment cure']), ('First-line drugs for drug-susceptible TB are:', ['Isoniazid, rifampicin, pyrazinamide, ethambutol','Bedaquiline, linezolid, clofazimine, delamanid','Levofloxacin, amikacin, cycloserine, ethionamide','Rifampicin, vancomycin, pyrazinamide, acyclovir']), ('The drug associated with optic neuritis is:', ['Ethambutol','Isoniazid','Rifampicin','Pyrazinamide']), ('Pyridoxine with isoniazid prevents:', ['Peripheral neuropathy','Optic neuritis','Hyperuricemia','QT prolongation']), ('Rifampicin commonly causes:', ['Enzyme induction and orange body fluids','Ototoxicity','Tendon rupture','Red-green blindness']), ('Pyrazinamide commonly causes:', ['Hyperuricemia','Neuropathy','QT prolongation','Ototoxicity']), ('MDR-TB is resistance to at least:', ['Isoniazid and rifampicin','Rifampicin alone','A fluoroquinolone only','All drugs']), ('Rifampicin resistance should lead to:', ['Full DST and DR-TB programme referral','Isoniazid monotherapy','No further testing','Stopping treatment']), ('A key principle of DR-TB treatment is:', ['Effective all-oral combination guided by DST','One active drug only','No toxicity monitoring','Injectables for every patient']), ('A core DR-TB medicine requiring QT monitoring is:', ['Bedaquiline','Pyridoxine','Isoniazid','Ethambutol']), ('Prolonged linezolid can cause:', ['Myelosuppression and neuropathy','Hyperuricemia','Orange urine','Tendon rupture']), ('Levofloxacin can cause:', ['Tendon injury and QT prolongation','Optic neuritis','Orange urine','Hypercalcemia']), ('Cycloserine can cause:', ['Neuropsychiatric toxicity','Optic neuritis','Hyperuricemia','Hepatic enzyme induction']), ('Aminoglycoside injectables can cause:', ['Ototoxicity and nephrotoxicity','Hypercalcemia','Optic neuritis','Orange tears']), ('NAAT assists TB care by:', ['Rapid TB detection and rifampicin-resistance testing','Diagnosing latent TB only','Proving cure','Replacing all DST']), ('Infectious pulmonary TB requires:', ['Airborne precautions plus effective treatment','Steroids alone','No contact review','Routine CT for all contacts']), ('Adherence support mainly:', ['Improves completion and reduces acquired resistance','Replaces microbiology','Prevents all toxicities','Avoids contact tracing']), ('DR-TB drug selection considers:', ['DST, prior exposure, comorbidity, interactions and programme guidance','Chest x-ray alone','Preference only','Serum ACE']), ('Bedaquiline plus clofazimine requires:', ['QT and interacting-drug review','Colour-vision testing only','Urate only','Bone density only']), ('Sarcoidosis is:', ['Multisystem noncaseating granulomatous inflammation','Bacterial infection','Lymphoma','IgE-mediated disease']), ('Typical chest radiograph finding:', ['Bilateral hilar lymphadenopathy','Unilateral pleural effusion','Cavity in all','Miliary nodules only']), ('Histologic hallmark:', ['Noncaseating granulomas','Caseating granulomas with AFB','Suppurative abscess','Amyloid']), ('Critical mimic before sarcoidosis diagnosis:', ['Tuberculosis','Hypertension','Osteoarthritis','Migraine']), ('Sarcoid hypercalcemia results from:', ['Macrophage activation of vitamin D','Calcitonin excess','Rifampicin induction','Renal calcium loss']), ('Erythema nodosum, ankle arthritis and BHL suggest:', ['Lofgren syndrome','Behcet syndrome','Felty syndrome','Goodpasture syndrome']), ('Palpitations or syncope in sarcoidosis suggest:', ['Cardiac sarcoidosis','Latent TB only','Hyperuricemia','Drug cure']), ('Baseline sarcoid assessment includes:', ['Eye examination','No systemic review','Colonoscopy','Bone marrow biopsy in all']), ('Serum ACE is:', ['Supportive but not diagnostic alone','Diagnostic alone','Always normal','A resistance marker']), ('Increased BAL CD4/CD8 ratio is:', ['Supportive but not diagnostic','Proof of TB','Specific for fungi','A contraindication to biopsy']), ('Scadding stage I is:', ['BHL without infiltrates','Fibrosis','Infiltrates without nodes','Normal CXR']), ('Scadding stage IV indicates:', ['Pulmonary fibrosis','BHL only','Normal imaging','Pleural effusion']), ('Asymptomatic stage I is often managed with:', ['Observation and monitoring','TB treatment','Emergency surgery','Chemotherapy']), ('First-line systemic treatment for organ-threatening sarcoidosis:', ['Corticosteroids','Bedaquiline','Isoniazid','Warfarin']), ('A steroid-sparing sarcoid agent is:', ['Methotrexate','Penicillin','Digoxin','Pyridoxine']), ('Chronic cutaneous sarcoidosis lesion:', ['Lupus pernio','Tinea versicolor','Zoster','Urticaria']), ('Heerfordt syndrome includes parotid enlargement, uveitis, fever and:', ['Facial palsy','Aortic dissection','Nephrosis','Hemoptysis']), ('A neurologic sarcoid manifestation is:', ['Facial nerve palsy','Appendicitis','Fracture','Migraine only']), ('Advanced pulmonary sarcoidosis may cause death from:', ['Fibrosis and respiratory failure','Tonsillitis','Ulcer disease','Cataract']), ('M tuberculosis culture from tissue favors:', ['TB over sarcoidosis','Sarcoidosis','Lofgren syndrome','Drug toxicity']), ('Rifampicin interactions arise from:', ['Hepatic enzyme induction','Universal enzyme inhibition','QT prevention','Hypercalcemia']), ('Linezolid needs:', ['Blood count and neurologic monitoring','No monitoring','Only eye testing','Only urate testing']), ('Injectables in DR-TB are:', ['Not routinely preferred with effective all-oral options','Mandatory for all','Latent TB therapy','A substitute for DST']), ('An abnormal ECG in sarcoidosis suggests:', ['Cardiac involvement','Latent infection only','Hyperuricemia','Cure']), ('Best sarcoidosis diagnostic framework:', ['Compatible pattern, granulomas when needed, exclusion of mimics','ACE alone','Steroid response alone','CT alone']), ('Fever and productive cough on sarcoid immunosuppression needs:', ['Infection assessment including TB where relevant','Automatic steroid escalation','No investigation','Isoniazid alone']), ('A WHO-described 6-month all-oral DR-TB regimen includes bedaquiline, delamanid, linezolid, levofloxacin and:', ['Clofazimine','Ethambutol','Isoniazid','Streptomycin']), ('DR-TB QTc prolongation requires:', ['Review QT-prolonging drugs and specialist-guided adjustment','No change','Stop all treatment alone','Ethambutol monotherapy']), ('Complex DR-TB should be managed with:', ['Specialist or national TB programme support','Self-selected drugs','Chest x-ray only','No culture follow-up']), ('Multiple active TB drugs are used to:', ['Prevent selection of resistant bacilli','Eliminate monitoring','Avoid infection control','Remove interactions'])] short=[ ('Short Case 1','A 32-year-old man has 6 weeks of cough, weight loss, evening fever, night sweats and hemoptysis. Chest x-ray shows an upper-lobe cavity.',['List four tests to confirm TB and assess resistance.','State immediate infection-control and public-health actions.','Name first-line medicines and one key toxicity of each.']), ('Short Case 2','A molecular test detects M tuberculosis with rifampicin resistance.',['Define rifampicin-resistant TB and MDR-TB.','List four principles for choosing a DR-TB regimen.','Name four DR-TB medicines and two monitoring needs.']), ('Short Case 3','A patient on HRZE develops jaundice, nausea and dark urine after 3 weeks.',['Identify the likely serious adverse effect.','Outline immediate clinical and laboratory assessment.','State treatment interruption and reintroduction principles.']), ('Short Case 4','A 38-year-old woman has dry cough, bilateral hilar adenopathy and noncaseating granulomas on biopsy.',['State the three pillars of diagnosis.','List four alternative diagnoses to exclude.','Name three baseline organ assessments.']), ('Short Case 5','A patient has tender red nodules on the shins, fever, ankle arthritis and BHL.',['Name the syndrome.','List two supportive findings.','Describe initial management and prognosis.']), ('Short Case 6','A patient receiving bedaquiline-containing DR-TB treatment has palpitations and prolonged QTc.',['Name three QT-prolongation contributors.','Outline immediate monitoring actions.','Explain why specialist/programme input is needed.'])] long=[ ('Long Case 1: Drug-Susceptible Pulmonary TB','A 41-year-old man with newly diagnosed HIV presents with fever, weight loss, cough and night sweats. Sputum NAAT confirms M tuberculosis without rifampicin resistance.',['Describe assessment for severity and extrapulmonary disease.','Outline first-line treatment, adherence support and preventive measures.','Describe toxicity and response monitoring.','Explain coordination of TB and antiretroviral treatment.','State contact and infection-control actions.']), ('Long Case 2: Rifampicin-Resistant / MDR-TB','A 29-year-old woman previously treated for pulmonary TB has smear-positive disease and a molecular test shows rifampicin resistance.',['Explain resistance testing and need for full DST.','Define MDR-TB and purpose of second- and third-line medicines.','Outline all-oral regimen construction under national/WHO guidance, with core and additional drugs.','Describe monitoring for bedaquiline, linezolid, fluoroquinolones, clofazimine, cycloserine and injectables if used.','Explain infection control, adherence, psychosocial support and microbiologic follow-up.']), ('Long Case 3: Pulmonary Sarcoidosis','A 45-year-old woman has dry cough, dyspnea, BHL and mediastinal adenopathy. Biopsy shows noncaseating granulomas.',['Formulate differentials and exclusion of infectious, occupational and malignant mimics.','Describe staging and baseline assessment.','State when observation versus treatment is appropriate.','Outline corticosteroid and steroid-sparing therapy.','Identify urgent referral red flags.']), ('Long Case 4: Multisystem Sarcoidosis','A 36-year-old woman with biopsy-confirmed sarcoidosis develops palpitations, presyncope, blurred vision, facial weakness, AV block and hypercalcemia.',['Identify organ-threatening manifestations and urgency.','Outline investigations and multidisciplinary referrals.','Describe acute and longer-term treatment, including hypercalcemia.','Explain screening for TB and infection before immunosuppression in endemic settings.','Provide monitoring for disease activity, toxicity and complications.'])] S=getSampleStyleSheet(); for n,base,size,leading,color,align in [('T','Title',16,20,'#1F4E79',TA_CENTER),('H1','Heading1',13,16,'#1F4E79',0),('H2','Heading2',11,14,'#1F4E79',0),('B','BodyText',9.2,12,'#000000',0),('Q','BodyText',9.2,12,'#000000',0),('O','BodyText',9,11,'#000000',0),('L','BodyText',8.4,10,'#444444',0)]: S.add(ParagraphStyle(n,parent=S[base],fontName='Helvetica-Bold' if n in ['T','H1','H2'] else 'Helvetica',fontSize=size,leading=leading,textColor=colors.HexColor(color),alignment=align,spaceBefore=7 if n in ['H1','H2','Q'] else 0,spaceAfter=4,leftIndent=14 if n=='O' else 0,firstLineIndent=-10 if n=='O' else 0,keepWithNext=n in ['H1','H2','Q'])) story=[Paragraph('Internal Medicine Examination',S['T']),Paragraph('Topics: Tuberculosis, Drug-Resistant TB, Second-Line and Third-Line Treatment Principles, and Sarcoidosis',S['B']),Paragraph('Candidate Name: _______________________________________ Date: ___________________',S['B']),Paragraph('Instructions',S['H1']),Paragraph('Section A contains 50 single-best-answer MCQs. Section B contains 10 clinical cases: 6 short cases and 4 long cases. Answer all questions. Drug-resistant TB regimens must follow current national TB programme/WHO guidance, DST, prior treatment and individual factors. No marking key is included.',S['B']),PageBreak(),Paragraph('SECTION A: Multiple-Choice Questions',S['H1']),Paragraph('50 questions. Select ONE best answer.',S['B'])] for i,(stem,opts) in enumerate(qs,1): story.append(Paragraph(f'<b>{i}.</b> {escape(stem)}',S['Q'])) for j,o in enumerate(opts): story.append(Paragraph(f'{chr(65+j)}. {escape(o)}',S['O'])) story += [PageBreak(),Paragraph('SECTION B: Clinical Cases',S['H1']),Paragraph('10 cases: 6 short cases and 4 long cases. Answer all parts clearly and concisely.',S['B']),Paragraph('Part I: Short Cases',S['H2'])] for title,stem,parts in short: story += [Paragraph(title,S['H2']),Paragraph(escape(stem),S['B'])] for j,x in enumerate(parts): story += [Paragraph(f'{chr(97+j)}. {escape(x)}',S['B']),Paragraph('_'*95,S['L']),Paragraph('_'*95,S['L'])] story += [PageBreak(),Paragraph('Part II: Long Cases',S['H2'])] for title,stem,parts in long: story += [Paragraph(title,S['H2']),Paragraph(escape(stem),S['B'])] for j,x in enumerate(parts): story += [Paragraph(f'{chr(97+j)}. {escape(x)}',S['B']),Paragraph('_'*95,S['L']),Paragraph('_'*95,S['L']),Paragraph('_'*95,S['L'])] story.append(Paragraph('End of Examination',S['H1'])) def hf(c,d): c.saveState();w,h=A4;c.setFont('Helvetica-Bold',7.5);c.setFillColor(colors.HexColor('#1F4E79'));c.drawCentredString(w/2,h-1.1*cm,'INTERNAL MEDICINE EXAMINATION | TUBERCULOSIS & SARCOIDOSIS');c.setStrokeColor(colors.HexColor('#1F4E79'));c.line(1.5*cm,h-1.25*cm,w-1.5*cm,h-1.25*cm);c.setFont('Helvetica',8);c.setFillColor(colors.black);c.drawCentredString(w/2,.8*cm,f'Page {d.page}');c.restoreState() SimpleDocTemplate(str(out),pagesize=A4,leftMargin=1.55*cm,rightMargin=1.55*cm,topMargin=1.6*cm,bottomMargin=1.25*cm,title='Internal Medicine TB Sarcoidosis Examination').build(story,onFirstPage=hf,onLaterPages=hf) print(out) PY python3 - <<'PY' from pypdf import PdfReader p='/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf';r=PdfReader(p);t='\n'.join(x.extract_text() or '' for x in r.pages) print('pages',len(r.pages),'size',__import__('os').path.getsize(p),'checks',[x in t for x in ['SECTION A: Multiple-Choice Questions','Short Case 6','Long Case 4: Multisystem Sarcoidosis','End of Examination','six-month all-oral DR-TB regimen']],'answerkey','Answer Key' in t) PY
Internal Medicine TB Sarcoidosis Examination
PDF Document · PDF
REMOVE THE WORD MARKING KEY MAKE IT OFFICIAL
~/internal-medicine-tb-sarcoidosis/output
python3 - <<'PY' import pdfplumber p='/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf' with pdfplumber.open(p) as pdf: for i,page in enumerate(pdf.pages[:2],1): text=page.extract_text() or '' print('PAGE',i, text[:2000]) for w in page.extract_words(): if 'marking' in w['text'].lower() or 'key' in w['text'].lower(): print('WORD',w) PY
python3 - <<'PY' from pypdf import PdfReader p='/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf' r=PdfReader(p); data=r.pages[0].get_contents().get_data() for term in [b'No marking',b'marking',b'key']: print(term,data.find(term)) print(data[data.find(b'marking')-200:data.find(b'marking')+150]) PY
python3 - <<'PY' from pypdf import PdfReader, PdfWriter from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from io import BytesIO from pathlib import Path src=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf') out=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Official_Examination.pdf') reader=PdfReader(str(src)); writer=PdfWriter() packet=BytesIO(); c=canvas.Canvas(packet,pagesize=A4) # Remove the candidate-paper wording containing the words "marking key" on page 1. c.setFillColor(colors.white); c.rect(40,668,520,24,stroke=0,fill=1) c.setFillColor(colors.black); c.setFont('Helvetica',9.2) c.drawString(72,677,'All questions are compulsory. This is an official candidate examination paper.') c.save(); packet.seek(0) overlay=PdfReader(packet).pages[0] for i,p in enumerate(reader.pages): if i==0: p.merge_page(overlay) writer.add_page(p) writer.add_metadata({'/Title':'Official Internal Medicine Examination: Tuberculosis and Sarcoidosis','/Subject':'Candidate Examination Paper','/Author':'Examination Office'}) with open(out,'wb') as f: writer.write(f) print(out) PY python3 - <<'PY' import pdfplumber from pypdf import PdfReader p='/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Official_Examination.pdf' with pdfplumber.open(p) as pdf: text=pdf.pages[0].extract_text() or '' print('visual replacement:', 'official candidate examination paper' in text.lower()) print(text[:900]) r=PdfReader(p) print('pages',len(r.pages),'bytes',__import__('os').path.getsize(p)) PY
python3 - <<'PY' from pypdf import PdfReader, PdfWriter from pypdf.generic import DecodedStreamObject, NameObject from pathlib import Path src=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Examination.pdf') out=Path('/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Official_Examination.pdf') r=PdfReader(str(src)); w=PdfWriter() for i,page in enumerate(r.pages): if i == 0: content=page.get_contents().get_data() old=b'No marking key is included.' if old not in content: raise RuntimeError('Target wording not found') content=content.replace(old,b'') stream=DecodedStreamObject(); stream.set_data(content) page[NameObject('/Contents')]=stream w.add_page(page) w.add_metadata({'/Title':'Official Internal Medicine Examination - Tuberculosis and Sarcoidosis','/Subject':'Candidate Examination Paper','/Author':'Examination Office','/Creator':'Examination Office'}) with open(out,'wb') as f:w.write(f) print(out) PY python3 - <<'PY' import pdfplumber from pypdf import PdfReader p='/tmp/workspace/internal-medicine-tb-sarcoidosis/output/Internal_Medicine_TB_Sarcoidosis_Official_Examination.pdf' with pdfplumber.open(p) as pdf: text='\n'.join(page.extract_text() or '' for page in pdf.pages) print('marking:', 'marking' in text.lower(), 'key:', 'key' in text.lower()) print('core sections:', [x in text for x in ['SECTION A: Multiple-Choice Questions','SECTION B: Clinical Cases','Short Case 6','Long Case 4: Multisystem Sarcoidosis','End of Examination']]) print('pages',len(PdfReader(p).pages),'bytes',__import__('os').path.getsize(p)) PY
Internal Medicine TB Sarcoidosis Official Examination
PDF Document · PDF