"""MIT License, copyright2026 Doutora Flávia — Caderno de dados públicos. Own code only. Original Anvisa files are obtained separately and not relicensed. Offline reproduction of selected aggregate facts; no network/credentials/patients. """ from pathlib import Path from decimal import Decimal,getcontext import argparse,collections,csv,hashlib,json,re,unicodedata,zipfile import xml.etree.ElementTree as ET PINS={2024:'c7b24c0e3b9a1059b474bca96b6d7ecfe33ee943e9080a9a35d27cc355d55ada',2025:'5d6e1ebf53b6194a03467806f028fb9603d0a9a207df5fee54ffc0bb51aaeb35'} FIELDS={'BI':'obtida_cm2','BU':'liberada_cm2','BV':'entregue_cm2','BW':'uso_notificado_cm2'} NS={'m':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'} getcontext().prec=30 def norm(s):return re.sub(r'\s+',' ',unicodedata.normalize('NFKC',str(s))).strip() def parse(source,year): p=source/f'production-{year}.xlsx' assert hashlib.sha256(p.read_bytes()).hexdigest()==PINS[year], f'Wrong source edition: {p.name}; stop rather than silently compare revisions' with zipfile.ZipFile(p) as z: strings=[''.join(x.itertext()) for x in ET.fromstring(z.read('xl/sharedStrings.xml')).findall('m:si',NS)] wb=ET.fromstring(z.read('xl/workbook.xml')) rels={x.attrib['Id']:x.attrib['Target'] for x in ET.fromstring(z.read('xl/_rels/workbook.xml.rels'))} sh=next(x for x in wb.find('m:sheets',NS) if x.attrib['name']=='PELE') target=rels[sh.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id']] target=target.lstrip('/') if target.startswith('/') else 'xl/'+target xml=ET.fromstring(z.read(target));rows=[] for r in xml.findall('m:sheetData/m:row',NS): cells={} for c in r.findall('m:c',NS): col=re.match('[A-Z]+',c.attrib['r']).group();v=c.find('m:v',NS);value=v.text if v is not None else None if c.attrib.get('t')=='s' and value is not None:value=strings[int(value)] if c.attrib.get('t')=='inlineStr':value=''.join(c.find('m:is',NS).itertext()) cells[col]=(value,c.attrib.get('t','n')) rows.append((r.attrib['r'],cells)) heads={k:v[0] for k,v in rows[0][1].items()};records=[];cached_total={} for rownum,c in rows[1:]: if c.get('A',(None,))[0]=='TOTAL': cached_total={key:Decimal(c[col][0]) for col,key in FIELDS.items()};continue if norm(c.get('A',(None,))[0])!=str(year) or not c.get('E',(None,))[0]:continue row=dict(zip(('ano','semestre','UF_banco','municipio_banco','banco_nome_fonte'),[norm(c.get(x,(None,))[0]) for x in ('A','B','C','D','E')])) row['linha_XML_fonte']=rownum for col,key in FIELDS.items(): value,t=c[col];assert t=='n' and value is not None value=Decimal(value);assert value.is_finite() and value>=0;row[key]=value records.append(row) return heads,records,cached_total def write_csv(out,name,rows): with (out/name).open('w',encoding='utf-8-sig',newline='') as f: w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows([{k:format(v,'f') if isinstance(v,Decimal) else v for k,v in r.items()} for r in rows]) def main(): ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--source-dir',type=Path,required=True);ap.add_argument('--output-dir',type=Path,required=True);args=ap.parse_args() out=args.output_dir.resolve();src=args.source_dir.resolve();assert out!=src,'Use a separate output directory';out.mkdir(parents=True,exist_ok=True) parsed={y:parse(src,y) for y in PINS};records=[r for y in PINS for r in parsed[y][1]] assert all(norm(parsed[2024][0][c])==norm(parsed[2025][0][c]) for c in FIELDS) keys=[tuple(r[k] for k in ('ano','semestre','UF_banco','municipio_banco','banco_nome_fonte')) for r in records] assert len(records)==len(set(keys))==16 frame=lambda year:sorted(tuple(r[k] for k in ('semestre','UF_banco','municipio_banco','banco_nome_fonte')) for r in parsed[year][1]) assert frame(2024)==frame(2025) annual=[] for key in FIELDS.values(): a=sum((r[key] for r in records if r['ano']=='2024'),Decimal(0));b=sum((r[key] for r in records if r['ano']=='2025'),Decimal(0)) annual.append({'medida':key,'2024':a,'2025':b,'diferenca_2025_menos_2024':b-a,'variacao_percentual_mesma_medida':(b-a)/a*100 if a else None}) banks=[] for uf,city,bank in sorted(set((r['UF_banco'],r['municipio_banco'],r['banco_nome_fonte']) for r in records)): for key in FIELDS.values(): totals={y:sum((r[key] for r in records if r['ano']==y and r['UF_banco']==uf and r['municipio_banco']==city and r['banco_nome_fonte']==bank),Decimal(0)) for y in ('2024','2025')} banks.append({'UF_banco':uf,'municipio_banco':city,'banco_nome_fonte':bank,'medida':key,'2024':totals['2024'],'2025':totals['2025'],'diferenca_2025_menos_2024':totals['2025']-totals['2024']}) semesters=[{'ano':y,'semestre':sem,**{key:sum((r[key] for r in records if r['ano']==y and r['semestre']==sem),Decimal(0)) for key in FIELDS.values()}} for y in ('2024','2025') for sem in ('Janeiro a Junho','Julho a Dezembro')] reconciliation=[{'ano':'2024','medida':a['medida'],'soma_das_linhas_cm2':a['2024'],'total_armazenado_fonte_cm2':parsed[2024][2][a['medida']],'diferenca_cm2':a['2024']-parsed[2024][2][a['medida']]} for a in annual] for name,rs in [('pele-registros-semestrais.csv',records),('pele-totais-anuais.csv',annual),('pele-totais-por-banco.csv',banks),('pele-totais-semestrais.csv',semesters),('reconciliation.csv',reconciliation)]:write_csv(out,name,rs) report={'source_sha256':PINS,'rows':len(records),'unit':'cm², bank-semester reporting facts, not people, cohorts, current stock, quality or outcomes','annual':annual,'reconciliation':reconciliation,'original_files_not_redistributed':True} (out/'reproduction-results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2,default=lambda x:format(x,'f'))+'\n',encoding='utf-8') print('Offline reproduction complete:16 records,5 CSV files,1 result JSON. No network or clinical inference.') if __name__=='__main__':main()