Files
Investidor-V2/outputs/investmoz-fintech-correspondencia-20261015/inventory-extract.py
T
nala 6a76aac80f
tests / ci (push) Canceled after 0s
versao compilada 1
2026-10-16 09:17:28 +02:00

31 lines
3.5 KiB
Python

from pathlib import Path
import csv,json,hashlib,subprocess,unicodedata,zipfile,xml.etree.ElementTree as ET,datetime
root=Path(__file__).resolve().parents[2];out=Path(__file__).parent;corpus=Path('C:/Mac/Home/Documents/TEMPO/Portal Tempo');pdfexe=Path('C:/laragon/bin/git/mingw64/bin/pdftotext.exe')
norm=lambda s:unicodedata.normalize('NFKD',s.lower()).encode('ascii','ignore').decode()
files=sorted([p for p in corpus.rglob('*') if p.is_file()]);allmeta=[{'path':str(p),'bytes':p.stat().st_size,'modified_ns':p.stat().st_mtime_ns} for p in files]
# Inventory every available original/attachment in the known corpus before selecting this consumer.
(out/'INVENTARIO-ACERVO-ACESSIVEL-LOCAL.json').write_text(json.dumps({'at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'root':str(corpus),'files':allmeta,'selection_not_a_publication':True},ensure_ascii=False,indent=2),encoding='utf-8')
hist=[]
for f,delimiter,pathkey in [('docs/investmoz/v2/auditoria-portal/inventario-fontes.csv',',','Exemplar/caminho'),('docs/investmoz/document-corpus-inventory-2026-10-06.csv',';','Path')]:
a=list(csv.DictReader((root/f).read_text('utf-8-sig').splitlines(),delimiter=delimiter));hist.append({'inventory':f,'records':len(a),'currently_accessible_paths':sum(Path(x.get('Caminho atual/alias') or x.get(pathkey,'')).is_file() for x in a)})
selected=[]
for p in files:
n=norm(p.name);rel=str(p.relative_to(corpus));pathnorm=norm(rel)
if p.name.startswith('~$'):continue
pdf=p.suffix.lower()=='.pdf' and any(k in n for k in ['20-2020','50-2024','decreto_50','licenciamento-de-empresas-prestadoras-de-servicos-de-pagamentos','licenciamento-de-bancos-e-sociedades','licenciamento-de-microbancos','lei-cambial','branqueamento de capitais','registo e licenciamento de provedores'])
docx=p.suffix.lower()=='.docx' and ('licenciamento bm/' in pathnorm.replace('\\','/') or '/bm/' in pathnorm.replace('\\','/') or n=='fintech e tic.docx' or 'checklist para consultoria financeira' in n)
if not (pdf or docx):continue
h=hashlib.sha256(p.read_bytes()).hexdigest();ident='SRC-'+h[:12];target=out/'extracoes'/f'{ident}.txt';target.parent.mkdir(exist_ok=True)
if pdf:
subprocess.run([str(pdfexe),'-layout','-enc','UTF-8',str(p),str(target)],check=True,capture_output=True)
else:
with zipfile.ZipFile(p) as z:
doc=ET.fromstring(z.read('word/document.xml'));ns={'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
paras=[''.join(x.itertext()) for x in []]
paras=[''.join(t.text or '' for t in el.findall('.//w:t',ns)) for el in doc.findall('.//w:p',ns)]
target.write_text('\n'.join(paras),encoding='utf-8')
selected.append({'id':ident,'path':str(p),'relative_path':rel,'name':p.name,'bytes':p.stat().st_size,'sha256':h,'extraction':str(target.relative_to(out)),'text_characters':len(target.read_text('utf-8')),'kind':'official-text-or-guide-to-classify' if pdf else 'supporting-document-not-presumed-official'})
proof={'at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'corpus_inventory_files':len(files),'corpus_bytes':sum(x['bytes'] for x in allmeta),'historical_inventories':hist,'selected_sources_and_support':selected,'no_provenance_revalidation':True,'publications':0,'active_changes':0}
(out/'FONTES-E-SUPORTES.json').write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps({'files_inventoried':len(files),'historical_inventories':hist,'selected':selected},ensure_ascii=True))