64 lines
5.7 KiB
Python
64 lines
5.7 KiB
Python
from pathlib import Path
|
|
import datetime,hashlib,json,os,zipfile,xml.etree.ElementTree as ET,csv,io
|
|
root=Path(__file__).resolve().parents[2];out=Path(__file__).resolve().parent
|
|
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
|
|
previous=root/'outputs/investmoz-parques-mapa-20261016/INVENTARIO-ACERVO.json'
|
|
old=json.loads(previous.read_text('utf-8'));corpus=Path(old['corpus_inventory_reused']['root'])
|
|
def inventory(folder):
|
|
result=[];errors=[]
|
|
if not folder.is_dir():return [],[{'path':str(folder),'error':'unavailable'}]
|
|
for base,dirs,files in os.walk(folder,followlinks=False,onerror=lambda e:errors.append({'path':e.filename,'error':type(e).__name__})):
|
|
for name in sorted(files):
|
|
p=Path(base)/name
|
|
try:
|
|
s=p.stat();result.append({'path':str(p),'bytes':s.st_size,'modified_ns':s.st_mtime_ns,'suffix':p.suffix.lower()})
|
|
except OSError as e:errors.append({'path':str(p),'error':type(e).__name__})
|
|
return result,errors
|
|
files,errors=inventory(corpus);attachments,ae=inventory(Path('C:/Users/macbook/.codex/attachments'))
|
|
all_inventory={'at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'corpus_root':str(corpus),'corpus_files':files,'attachments':attachments,
|
|
'errors':errors+ae,'previous_inventory':{'path':previous.relative_to(root).as_posix(),'sha256':sha(previous),'prior_corpus_count':len(old['corpus_files'])},
|
|
'selection_started_after_complete_inventory':True,'active_database_connections':0}
|
|
(out/'INVENTARIO-ACERVO-PRIVADO.json').write_text(json.dumps(all_inventory,ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
old_sources=json.loads((root/'outputs/investmoz-parques-mapa-20261016/FONTES-LEVANTADAS.json').read_text('utf-8'))['sources']
|
|
sources=[];excerpts=[];private=[]
|
|
for item in old_sources:
|
|
p=Path(item['path'])
|
|
if not p.is_file():sources.append({'name':p.name,'available':False,'previous_sha256':item.get('sha256')});continue
|
|
entry={'name':p.name,'available':True,'bytes':p.stat().st_size,'sha256':sha(p),'matches_previous_exemplar':sha(p)==item.get('sha256'),
|
|
'origin':'existing project instruction/compilation'if p.suffix.lower()=='.docx'else'existing application reconciliation/history','embedded_resources':[]}
|
|
paras=[]
|
|
if p.suffix.lower()=='.docx':
|
|
with zipfile.ZipFile(p)as z:
|
|
ns={'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'};tree=ET.fromstring(z.read('word/document.xml'))
|
|
paras=[''.join(n.text or ''for n in para.findall('.//w:t',ns))for para in tree.findall('.//w:p',ns)]
|
|
entry['embedded_resources']=[{'entry':x.filename,'bytes':x.file_size,'CRC32':format(x.CRC,'08x')}for x in z.infolist()if not x.is_dir()and(x.filename.startswith('word/media/')or x.filename.startswith('word/embeddings/'))]
|
|
entry['paragraphs']=len(paras)
|
|
positions=set()
|
|
if entry['sha256'].startswith('d0c06a75'):positions.update(range(3540,3655));positions.update(range(4445,4465))
|
|
elif entry['sha256'].startswith('e1169a77'):
|
|
for i,t in enumerate(paras):
|
|
if any(k in t.casefold()for k in ['ficha operacional','ficha do parque','ficha por parque','lotes internos','modelo de gestão']):positions.update(range(max(0,i-3),min(len(paras),i+16)))
|
|
else:positions.update(range(len(paras)))
|
|
relevant=[{'paragraph':i+1,'text':paras[i]}for i in sorted(positions)if i<len(paras)and paras[i].strip()]
|
|
excerpts.append({'name':p.name,'sha256':entry['sha256'],'paragraphs':relevant})
|
|
sources.append(entry);private.append({'path':str(p),**entry})
|
|
(out/'FONTES-EXCERTOS-PRIVADOS.json').write_text(json.dumps(excerpts,ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
(out/'FONTES-CAMINHOS-PRIVADOS.json').write_text(json.dumps(private,ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
(out/'MANIFESTO-FONTES.json').write_text(json.dumps({'inventory_at':all_inventory['at'],'corpus_count':len(files),'attachments_count':len(attachments),
|
|
'inventory_private_sha256':sha(out/'INVENTARIO-ACERVO-PRIVADO.json'),'inventory_errors':len(errors+ae),'sources':sources,
|
|
'official_provenance_revalidation':False,'new_external_research':False,'note':'No factual claim is updated merely by inventorying an exemplar.'},ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
receipt=json.loads((root/'outputs/investmoz-parques-ativacao-20261016/para-revisao/RECIBO-INTEGRIDADE-FINAL.json').read_text('utf-8'))
|
|
paths={p.relative_to(root).as_posix():sha(p)for f in ['app','config','routes','database','resources','public/build']for p in(root/f).rglob('*')if p.is_file()}
|
|
baseline={'files':paths,'protected':{n:sha(root/n)for n in ['.env','composer.lock','package-lock.json']},
|
|
'matrix':sha(root/'docs/investmoz/v2/auditoria-portal/matriz-requisitos.csv'),'backlog':sha(root/'docs/investmoz/v2/auditoria-portal/backlog.md')}
|
|
assert baseline['matrix']==receipt['matrix_sha256'] and baseline['backlog']==receipt['backlog_sha256']
|
|
(out/'BASELINE-ATIVO.json').write_text(json.dumps(baseline,indent=2)+'\n','utf-8')
|
|
matrix=root/'docs/investmoz/v2/auditoria-portal/matriz-requisitos.csv';csv.field_size_limit(10000000)
|
|
r=csv.DictReader(io.StringIO(matrix.read_text('utf-8-sig'),newline=''))
|
|
ids=set(json.loads((root/'outputs/investmoz-parques-ativacao-20261016/MATRIZ-ATUALIZACAO.json').read_text('utf-8'))['rows_updated'])
|
|
rows=[x for x in r if x['ID']in ids]
|
|
(out/'REQUISITOS-EXISTENTES.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
print(json.dumps({'complete_inventory_before_selection':True,'corpus_files':len(files),'attachments':len(attachments),'errors':len(errors+ae),
|
|
'selected_sources':len(sources),'unchanged_exemplars':sum(x.get('matches_previous_exemplar',False)for x in sources),
|
|
'runtime_baseline_files':len(paths),'existing_requirement_rows':len(rows),'active_connections':0}))
|