from pathlib import Path from datetime import datetime,timezone import csv,hashlib,json,re,zipfile,xml.etree.ElementTree as ET ROOT=Path(__file__).resolve().parents[2];OUT=Path(__file__).resolve().parent csv.field_size_limit(10000000) with (ROOT/'docs/investmoz/v2/auditoria-portal/matriz-requisitos.csv').open(encoding='utf-8-sig',newline='')as f:rows=list(csv.DictReader(f)) sources=json.loads((OUT/'source-availability.json').read_text(encoding='utf-8')); namespace={'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'} masterroot=Path('C:/Mac/Home/Documents/TEMPO/Portal Tempo/Servicos Tempo') records=[] for entry in sources: p=Path(entry['resolved_path']) if entry['embedded_member']:continue if not p.is_file() and p.name=='Checklist para consultoria financeira.docx': found=list(masterroot.rglob(p.name)) for candidate in found: digest=hashlib.sha256(candidate.read_bytes()).hexdigest() if digest==entry['expected_sha256']:entry.update(resolved_path=str(candidate),original_exists=True,current_sha256=digest,size=candidate.stat().st_size,same_bytes=True,original_reference_preserved=entry['reference'],alias_recovered_by_same_hash=True);p=candidate;break if p.suffix.lower()!='.docx' or not p.is_file():continue if p.name.startswith('~$'):continue try: with zipfile.ZipFile(p)as z: xml=ET.fromstring(z.read('word/document.xml')) paragraphs=[''.join(t.text or '' for t in q.findall('.//w:t',namespace)) for q in xml.findall('.//w:p',namespace)] media=[n for n in z.namelist() if n.startswith('word/media/') and not n.endswith('/')] mediahashes={n:hashlib.sha256(z.read(n)).hexdigest() for n in media} references=[r['ID'] for r in rows if p.name.casefold() in (r['Fonte/ocorrĂȘncias']+' '+r['VersĂ”es divergentes']).casefold()] record={'path':str(p),'name':p.name,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'paragraphs':len(paragraphs),'embedded_media':mediahashes,'existing_requirement_ids':references,'version_changed_from_inventory':not entry.get('same_bytes',False)} if 'Gestao de perfis investeMOZ v1' in p.name: record['profile_restriction_sections']=[{'xml_paragraph':i+1,'text':t}for i,t in enumerate(paragraphs)if any(w in t.casefold()for w in ['mfa','minuto','suporte','coordenador','independen','superutil','promotor','validador','publicador'])] (OUT/'profiles-source-sections.json').write_text(json.dumps(record,ensure_ascii=False,indent=2),encoding='utf-8') if p.name=='Prompt a serem aplicados .docx': record['current_sections']=[{'xml_paragraph':i+1,'text':t}for i,t in enumerate(paragraphs)if t.strip()] (OUT/'changed-prompt-sections.json').write_text(json.dumps(record,ensure_ascii=False,indent=2),encoding='utf-8') records.append(record) except (ValueError,OSError,zipfile.BadZipFile,KeyError,ET.ParseError) as error:records.append({'path':str(p),'error_type':type(error).__name__}) (OUT/'source-availability-reconciled.json').write_text(json.dumps(sources,ensure_ascii=False,indent=2),encoding='utf-8') (OUT/'DOCX-reference-index.json').write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf-8') print(json.dumps({'DOCX_exemplars_parsed':len(records),'changed_current_prompt_present':(OUT/'changed-prompt-sections.json').exists(),'checklist_alias_recovered':any(r.get('alias_recovered_by_same_hash')for r in sources),'sources_not_reimported':True,'new_requirement_ids':0}))