46 lines
3.5 KiB
Python
46 lines
3.5 KiB
Python
from pathlib import Path
|
|
import json,hashlib,zipfile,xml.etree.ElementTree as E,unicodedata,sys
|
|
root=Path(__file__).resolve().parents[2];out=Path(__file__).resolve().parent
|
|
historical=root/'outputs/investmoz-fintech-correspondencia-20261015/INVENTARIO-ACERVO-ACESSIVEL-LOCAL.json'
|
|
inventory=json.loads(historical.read_text('utf-8'))
|
|
norm=lambda s:unicodedata.normalize('NFKD',s.casefold()).encode('ascii','ignore').decode()
|
|
keys=['cae ebau','classificacao das actividades','upgrade do portal de investimentos v5','upgrade do portal de investimentos v6','agronegocio','inteligencia_economica_cae','implementacao da cae']
|
|
selected=[r for r in inventory['files'] if (any(k in norm(r['path']) for k in keys) or norm(Path(r['path']).name) in ['cae.docx','cae cnbs.docx']) and Path(r['path']).suffix.lower() in ['.docx','.xlsx'] and not Path(r['path']).name.startswith(('._','~$'))]
|
|
cache={x['path']:x for x in json.loads((out/'FONTES-EXTRAIDAS.json').read_text('utf-8'))['selection']} if (out/'FONTES-EXTRAIDAS.json').exists() else {}
|
|
result={'inventory_reused':str(historical.relative_to(root)),'inventory_sha256':hashlib.sha256(historical.read_bytes()).hexdigest(),'all_corpus_files_in_inventory':len(inventory['files']),'selection':[]}
|
|
for r in selected:
|
|
p=Path(r['path']);print(json.dumps({'reading':str(p)},ensure_ascii=True),flush=True)
|
|
if str(p) in cache and 'error' not in cache[str(p)]:
|
|
result['selection'].append(cache[str(p)]);continue
|
|
try:
|
|
raw=p.read_bytes();item={'path':str(p),'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest()}
|
|
with zipfile.ZipFile(p) as z:
|
|
if p.suffix.lower()=='.docx':
|
|
doc=E.fromstring(z.read('word/document.xml'));ns={'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
|
|
item['paragraphs']=[{'paragraph':i,'text':''.join(e.itertext())} for i,e in enumerate(doc.findall('.//w:p',ns),1)]
|
|
item['paragraphs']=[{'paragraph':i,'text':''.join(t.text or '' for t in e.findall('.//w:t',ns))} for i,e in enumerate(doc.findall('.//w:p',ns),1)]
|
|
else:
|
|
ns={'s':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
|
|
shared=[]
|
|
if 'xl/sharedStrings.xml' in z.namelist():
|
|
shared=[''.join(t.text or '' for t in e.findall('.//s:t',ns)) for e in E.fromstring(z.read('xl/sharedStrings.xml')).findall('s:si',ns)]
|
|
sheets=E.fromstring(z.read('xl/workbook.xml')).findall('s:sheets/s:sheet',ns)
|
|
rels={e.attrib['Id']:e.attrib['Target'] for e in E.fromstring(z.read('xl/_rels/workbook.xml.rels'))}
|
|
item['sheets']=[]
|
|
for sheet in sheets:
|
|
target=rels[sheet.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id']]
|
|
target=target.lstrip('/') if target.startswith('/') else 'xl/'+target
|
|
cells=[]
|
|
for c in E.fromstring(z.read(target)).findall('.//s:sheetData/s:row/s:c',ns):
|
|
value=c.findtext('s:v',default='',namespaces=ns)
|
|
if c.attrib.get('t')=='s':value=shared[int(value)] if value else ''
|
|
elif c.attrib.get('t')=='inlineStr':value=''.join(t.text or '' for t in c.findall('.//s:t',ns))
|
|
if value:cells.append({'cell':c.attrib['r'],'value':value})
|
|
item['sheets'].append({'name':sheet.attrib['name'],'cells':cells})
|
|
result['selection'].append(item)
|
|
(out/'FONTES-EXTRAIDAS.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
except Exception as e:
|
|
result['selection'].append({'path':str(p),'error':type(e).__name__+': '+str(e)})
|
|
(out/'FONTES-EXTRAIDAS.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n','utf-8')
|
|
print(json.dumps({'sources':len(result['selection'])}),flush=True)
|