"""Offline reproduction of five CSVs and key checks from the reviewed Annex VI. MIT licensed original code. Dependency: beautifulsoup4. No network functionality. Input: original HTML saved from the exact Anvisalegis source URL in REPRODUCTION.txt. This program refuses another source vintage rather than silently mixing versions. """ from pathlib import Path from decimal import Decimal, ROUND_HALF_UP from collections import defaultdict, Counter import argparse, csv, hashlib, json, re from bs4 import BeautifulSoup SOURCE_SHA = 'd4dbf890888f5830962864cec95b8300794c493c57029b5f36eadaf5a38c355a' def monetary_cents(text): value = re.sub(r'\s+', ' ', text).strip().replace('R$', '').strip() if value in ('', '-', '–', '—'): return None if not re.fullmatch(r'(?:\d{1,3}(?:\.\d{3})*|\d+),\d{2}', value): raise ValueError('Unexpected monetary field; no silent coercion.') return int(Decimal(value.replace('.', '').replace(',', '.')) * 100) def percentage(part, total): return str((Decimal(part) * 100 / Decimal(total)).quantize(Decimal('.01'), rounding=ROUND_HALF_UP)) def write_csv(directory, name, rows): with (directory/name).open('x', encoding='utf8', newline='') as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])); writer.writeheader(); writer.writerows(rows) def reproduce(source, directory): raw = source.read_bytes() if hashlib.sha256(raw).hexdigest() != SOURCE_SHA: raise ValueError('Source SHA differs from reviewed vintage. Do not use its results as a reproduction.') if directory.exists(): raise ValueError('Use a new output directory; existing files are preserved.') soup = BeautifulSoup(raw, 'html.parser', from_encoding='iso-8859-1') tables = soup.find_all('table') if len(tables) != 9: raise ValueError('Original table structure changed.') rows = [] for table_index in (6, 7, 8): for row_index, tr in enumerate(tables[table_index].find_all('tr'), 1): cells = [' '.join(cell.get_text(' ', strip=True).split()) for cell in tr.find_all(['td', 'th'], recursive=False)] if not (len(cells) == 6 and re.fullmatch('[A-Z]{2}', cells[0]) and re.fullmatch('\d{6}', cells[1])): continue if cells[3] not in ('ESTADUAL', 'MUNICIPAL'): raise ValueError('Unexpected management classification.') rows.append(dict(source_table_index=table_index, source_row_index=row_index, uf=cells[0], ibge_6_source=cells[1], municipality_source=cells[2], production_management=cells[3], estimate_2026_jun_dec_source=cells[4], annual_estimate_source=cells[5], estimate_2026_jun_dec_cents=monetary_cents(cells[4]), annual_estimate_cents=monetary_cents(cells[5]))) if len(rows) != 182 or len({(x['uf'], x['ibge_6_source'], x['production_management']) for x in rows}) != 182: raise ValueError('182 unique source keys were not reproduced.') annual = sum(x['annual_estimate_cents'] for x in rows) uf = defaultdict(lambda: {'source_rows':0, 'codes':set(), 'annual_estimate_cents':0, 'state_management_annual_cents':0, 'municipal_management_annual_cents':0, 'jun_dec_known_cents':0, 'jun_dec_missing_rows':0}) management = defaultdict(lambda: {'source_rows':0, 'annual_estimate_cents':0, 'jun_dec_known_cents':0, 'jun_dec_missing_rows':0}) sp = {} for r in rows: u, m = uf[r['uf']], management[r['production_management']] u['source_rows'] += 1; u['codes'].add(r['ibge_6_source']); m['source_rows'] += 1 a, b = r['annual_estimate_cents'], r['estimate_2026_jun_dec_cents'] u['annual_estimate_cents'] += a; m['annual_estimate_cents'] += a sphere = 'state_management_annual_cents' if r['production_management'] == 'ESTADUAL' else 'municipal_management_annual_cents' u[sphere] += a if b is None: u['jun_dec_missing_rows'] += 1; m['jun_dec_missing_rows'] += 1 else: u['jun_dec_known_cents'] += b; m['jun_dec_known_cents'] += b if r['uf'] == 'SP': locality = sp.setdefault(r['ibge_6_source'], {'ibge_6_source':r['ibge_6_source'], 'locality_source':r['municipality_source'], 'source_rows':0, 'annual_estimate_cents':0, 'state_management_annual_cents':0, 'municipal_management_annual_cents':0, 'jun_dec_known_cents':0}) locality['source_rows'] += 1; locality['annual_estimate_cents'] += a locality[sphere] += a; locality['jun_dec_known_cents'] += b uf_rows = [dict(uf=k, source_rows=v['source_rows'], source_locality_codes=len(v['codes']), annual_estimate_cents=v['annual_estimate_cents'], annual_share_of_row_sum_percent=percentage(v['annual_estimate_cents'], annual), state_management_annual_cents=v['state_management_annual_cents'], municipal_management_annual_cents=v['municipal_management_annual_cents'], jun_dec_known_cents=v['jun_dec_known_cents'], jun_dec_missing_rows=v['jun_dec_missing_rows']) for k, v in uf.items()] uf_rows.sort(key=lambda x:(-x['annual_estimate_cents'], x['uf'])) management_rows = [dict(production_management=k, source_rows=v['source_rows'], annual_estimate_cents=v['annual_estimate_cents'], annual_share_of_row_sum_percent=percentage(v['annual_estimate_cents'], annual), jun_dec_known_cents=v['jun_dec_known_cents'], jun_dec_missing_rows=v['jun_dec_missing_rows']) for k, v in management.items()] sp_rows = sorted(sp.values(), key=lambda x:(-x['annual_estimate_cents'], x['ibge_6_source'])) for row in sp_rows: row['annual_share_of_SP_row_sum_percent'] = percentage(row['annual_estimate_cents'], uf['SP']['annual_estimate_cents']) partial = sum(x['estimate_2026_jun_dec_cents'] for x in rows if x['estimate_2026_jun_dec_cents'] is not None) reconciliation = [dict(measure='annual', source_rows=182, known_values=182, missing_values=0, sum_known_cents=annual, printed_total_cents=3710900000, known_sum_minus_printed_cents=annual-3710900000), dict(measure='2026_jun_dec', source_rows=182, known_values=181, missing_values=1, sum_known_cents=partial, printed_total_cents=2164691667, known_sum_minus_printed_cents=partial-2164691667)] directory.mkdir(parents=True) for name, data in [('annex-vi-source-rows.csv', rows), ('by-uf.csv', uf_rows), ('by-management.csv', management_rows), ('sp-localities.csv', sp_rows), ('reconciliation.csv', reconciliation)]: write_csv(directory, name, data) checks = {'source_sha256':SOURCE_SHA, 'source_rows':len(rows), 'source_locality_codes':len({r['ibge_6_source'] for r in rows}), 'UFs':len(uf), 'management_rows':dict(Counter(r['production_management'] for r in rows)), 'annual_row_sum_cents':annual, 'jun_dec_known_sum_cents':partial, 'annual_residual_cents':annual-3710900000, 'jun_dec_known_residual_cents':partial-2164691667, 'jun_dec_missing_rows':sum(r['estimate_2026_jun_dec_cents'] is None for r in rows), 'SP_annual_row_sum_cents':uf['SP']['annual_estimate_cents'], 'SP_annual_share_percent':percentage(uf['SP']['annual_estimate_cents'], annual), 'top3_UF_annual_share_percent':percentage(sum(x['annual_estimate_cents'] for x in uf_rows[:3]), annual), 'state_annual_share_percent':percentage(management['ESTADUAL']['annual_estimate_cents'], annual), 'SP_state_annual_share_percent':percentage(uf['SP']['state_management_annual_cents'], uf['SP']['annual_estimate_cents']), 'SP_capital_annual_share_within_SP_percent':percentage(sp['355030']['annual_estimate_cents'], uf['SP']['annual_estimate_cents']), 'not_measured':['Payments','Executed expenditure','Patients/procedures','Access or clinical outcomes'], 'publisher_summary_metadata_not_regenerated':'summary.json includes editorial source/limitation metadata; numerical checks and all five CSVs are reproduced here.'} (directory/'reproduction-checks.json').write_text(json.dumps(checks, ensure_ascii=False, indent=2), encoding='utf8') print(json.dumps(checks, ensure_ascii=False, indent=2)) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source-html', type=Path, required=True) parser.add_argument('--out', type=Path, required=True) args = parser.parse_args(); reproduce(args.source_html, args.out)