Carteira 4.3: simulação só de leitura da importação dos projectos âncora do PII
Junta os 15 âncoras e os 161 projectos integrados do relatório final do PII 2026–2030, as referências provinciais da MozParks e o inventário ANC (não oficial) num ficheiro de staging rastreável, e o comando portfolio:simulate-pii-import compara-os com a base: correspondências, candidatas oportunidade↔projecto, duplicações, localizações, custos ambíguos, relações pendentes e campos ausentes. Não grava nada. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
"""Builds database/data/pii-portfolio-staging.json for the read-only import simulation.
|
||||
|
||||
Usage:
|
||||
python3 -I tools/prepare-pii-portfolio-staging.py <PII.docx> <staging.csv> <projecto_ancora.docx> <output.json>
|
||||
|
||||
The documents are only read. Every row keeps its table/row reference and literal values;
|
||||
nothing is classified as approved, available or open for investment.
|
||||
"""
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
import docx
|
||||
|
||||
PII, STAGING, ANCHOR_DOC, OUTPUT = sys.argv[1:5]
|
||||
PII_SHA = 'bcbf8ec976100cc5e978aef54050c3e3e9d959b0d361fa80a788528a8e5049a6'
|
||||
# Table order in word/document.xml (counted from 1, as in pii-extraction-review-2026-10-03.md).
|
||||
# The anchor is taken from this order: several captions and keys in the source are wrong
|
||||
# (e.g. table 11 is A03 but its rows use "A02 - Cxx"; table 21 is A14 but its caption says A11).
|
||||
PROJECT_TABLES = {7: 'A01', 9: 'A02', 11: 'A03', 12: 'A04', 13: 'A05', 15: 'A06', 16: 'A07', 17: 'A08',
|
||||
18: 'A09', 19: 'A10', 20: 'A11', 21: 'A12', 23: 'A13', 24: 'A14', 25: 'A15'}
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(open(path, 'rb').read()).hexdigest()
|
||||
|
||||
|
||||
def rows(table):
|
||||
out = []
|
||||
for row in table.rows:
|
||||
cells, previous = [], None
|
||||
for cell in row.cells:
|
||||
if cell._tc is previous:
|
||||
continue
|
||||
previous = cell._tc
|
||||
cells.append(' '.join(cell.text.split()))
|
||||
out.append(cells)
|
||||
return out
|
||||
|
||||
|
||||
assert sha(PII) == PII_SHA, 'O DOCX do PII não coincide com o SHA-256 registado.'
|
||||
document = docx.Document(PII)
|
||||
tables = [rows(t) for t in document.tables]
|
||||
|
||||
anchors = []
|
||||
for number, row in enumerate(tables[5][1:], start=2):
|
||||
anchors.append({'code': row[0], 'name': row[1], 'region': row[2], 'sector': row[3],
|
||||
'source_table_index': 6, 'source_table_row': number, 'source_table_caption': 'Tabela 1. Legitimidade e Prioridade dos Projectos Âncora do PII 2026–2030'})
|
||||
assert [a['code'] for a in anchors] == [f'A{i:02d}' for i in range(1, 16)]
|
||||
|
||||
integrated = []
|
||||
with open(STAGING, encoding='utf-8-sig', newline='') as handle:
|
||||
staged = list(csv.DictReader(handle))
|
||||
assert len(staged) == 174
|
||||
for single in (7, 9):
|
||||
header, row = tables[single - 1][0], tables[single - 1][1]
|
||||
staged.insert(0 if single == 7 else 1, {
|
||||
'source_table_index': str(single), 'source_table_row': '2',
|
||||
'source_table_caption': f'Tabela {"2" if single == 7 else "4"}. Projecto {PROJECT_TABLES[single]}',
|
||||
'source_key_literal': row[0], 'source_title_literal': row[1], 'source_type_literal': row[2],
|
||||
'documented_relation_literal': row[3], 'source_location_literal': row[4], 'source_cost_literal': row[5],
|
||||
'source_currency_header_literal': header[5], 'source_horizon_literal': row[6],
|
||||
'review_flags': 'source_content_unverified|toponym_unverified|owner_review_required|currency_only_as_stated_in_table_header'})
|
||||
for item in staged:
|
||||
index = int(item['source_table_index'])
|
||||
anchor = PROJECT_TABLES[index]
|
||||
caption_code = re.search(r'Projecto (A?\d+)', item['source_table_caption'])
|
||||
flags = [f for f in item['review_flags'].split('|') if f]
|
||||
if caption_code and caption_code.group(1).lstrip('A').zfill(2) != anchor[1:]:
|
||||
flags.append('caption_anchor_differs_from_table_order')
|
||||
key = item['source_key_literal']
|
||||
if not key.replace(' ', '').startswith(anchor) and key not in ('-', ''):
|
||||
flags.append('source_key_differs_from_anchor')
|
||||
integrated.append({
|
||||
'anchor': anchor,
|
||||
'role': 'anchor' if item['source_type_literal'].startswith('Âncora') else 'complementary',
|
||||
'source_table_index': index, 'source_table_row': int(item['source_table_row']),
|
||||
'source_table_caption': item['source_table_caption'], 'source_key_literal': key,
|
||||
'title': item['source_title_literal'], 'type_literal': item['source_type_literal'],
|
||||
'relation_literal': item['documented_relation_literal'], 'location_literal': item['source_location_literal'],
|
||||
'cost_literal': item['source_cost_literal'], 'currency_header_literal': item['source_currency_header_literal'],
|
||||
'horizon_literal': item['source_horizon_literal'], 'review_flags': flags,
|
||||
})
|
||||
|
||||
provincial = []
|
||||
for number, row in enumerate(tables[7][1:], start=2):
|
||||
provincial.append({'province_literal': row[0], 'entries': [e.strip() for e in re.split(r',(?![^()]*\))', row[1]) if e.strip()],
|
||||
'sector_literal': row[2], 'source_table_index': 8, 'source_table_row': number,
|
||||
'source_table_caption': 'Tabela 3. Oportunidades de Projectos Integrados no Projecto Âncora Nacional',
|
||||
'note': 'Fonte indicada: MozParks (2025). Nomes de empresas e projectos existentes; não são oportunidades abertas.'})
|
||||
|
||||
anchor_doc = docx.Document(ANCHOR_DOC)
|
||||
anc_rows = rows(anchor_doc.tables[0])
|
||||
header = anc_rows[1]
|
||||
secondary = []
|
||||
for number, row in enumerate(anc_rows[2:], start=3):
|
||||
record = dict(zip(header, row))
|
||||
secondary.append({'id': record['ID'], 'province_literal': record['Província'], 'name': record['Projecto'],
|
||||
'sector_literal': record['Sector'], 'location_literal': record['Distrito/local'],
|
||||
'latitude_literal': record['Latitude'], 'longitude_literal': record['Longitude'],
|
||||
'investment_literal': record['Investimento divulgado'], 'promoter_literal': record['Promotor principal'],
|
||||
'employment_literal': record['Emprego divulgado'], 'status_literal': record['Estado em 2026'],
|
||||
'quality_literal': record['Qualidade'], 'source_table_row': number})
|
||||
|
||||
data = {
|
||||
'status': 'review_only_not_importable',
|
||||
'notice': 'Extracção para simulação de importação. Não é importação, validação institucional, aprovação oficial nem lista de oportunidades abertas.',
|
||||
'source': {'file': 'MPD_Relatório Final do PII 26-30_2111.docx', 'sha256': PII_SHA,
|
||||
'staging': 'docs/investmoz/source-staging/pii-26-30-review-only.csv (174 linhas) + tabelas 7 e 9 (A01, A02)',
|
||||
'table_numbering': 'Ordem em word/document.xml, a partir de 1'},
|
||||
'anchors': anchors,
|
||||
'integrated': integrated,
|
||||
'provincial_references': provincial,
|
||||
'secondary_inventory': {'file': 'projecto_ancora.docx', 'sha256': sha(ANCHOR_DOC),
|
||||
'notice': 'Inventário compilado de fontes diversas; não é o relatório do PII. Pontos são representativos e o próprio documento pede validação.',
|
||||
'records': secondary},
|
||||
}
|
||||
with open(OUTPUT, 'w', encoding='utf-8') as handle:
|
||||
json.dump(data, handle, ensure_ascii=False, indent=1)
|
||||
handle.write('\n')
|
||||
print(len(anchors), len(integrated), len(provincial), len(secondary))
|
||||
Reference in New Issue
Block a user