andrefelipe-afos
Peru 2026 electoral divergence — polls (36 first-round/14 candidates + 16 runoff) + docs + build pipeline
89cfe75 | /** | |
| * Parser determinístico das tabelas de pesquisas da Wikipedia "Opinion polling for the | |
| * 2026 Peruvian general election" (HTML renderizado via API). Materializa o grid respeitando | |
| * rowspan/colspan, mapeia colunas->candidatos pelo cabeçalho e extrai 1º turno (14 candidatos) | |
| * + 2º turno (Fujimori × Sánchez). Verifica contra valores conhecidos antes de gravar. | |
| * | |
| * Entrada: ../AFOS-Analitica-2026/.cache/peru-wiki.html (string HTML) | |
| * Saída: polls/peru-first-round-polls.csv (long), polls/peru-runoff-polls.csv, polls/peru-polls.json | |
| */ | |
| import { readFileSync, writeFileSync, mkdirSync } from 'fs' | |
| import { join } from 'path' | |
| const HTML = readFileSync(join(process.cwd(), '..', '..', 'AFOS-Analitica-2026', '.cache', 'peru-wiki.html'), 'utf-8') | |
| const OUT = join(process.cwd(), 'polls'); mkdirSync(OUT, { recursive: true }) | |
| const csv = (rows) => rows.map((r) => r.map((v) => { const s = String(v ?? ''); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s }).join(',')).join('\n') + '\n' | |
| // candidatos conhecidos: surname-chave -> {name, party} | |
| const CAND = { | |
| 'Fujimori': { name: 'Keiko Fujimori', party: 'Fuerza Popular' }, | |
| 'Sánchez': { name: 'Roberto Sánchez', party: 'Juntos por el Perú' }, | |
| 'López Aliaga': { name: 'Rafael López Aliaga', party: 'Renovación Popular' }, | |
| 'Nieto': { name: 'Jorge Nieto', party: 'Partido de Buen Gobierno' }, | |
| 'Belmont': { name: 'Ricardo Belmont', party: 'OBRAS' }, | |
| 'Álvarez': { name: 'Carlos Álvarez', party: 'País para Todos' }, | |
| 'López Chau': { name: 'Alfonso López Chau', party: 'Ahora Nación' }, | |
| 'Pérez Tello': { name: 'Marisol Pérez Tello', party: 'Demócrata Verde' }, | |
| 'Espá': { name: 'Carlos Espá', party: '' }, | |
| 'Olivera': { name: 'Fernando Olivera', party: 'Frente de la Esperanza' }, | |
| 'Luna': { name: 'José Luna', party: 'Podemos Perú' }, | |
| 'Lescano': { name: 'Yonhy Lescano', party: 'Cooperación Popular' }, | |
| 'Acuña': { name: 'César Acuña', party: 'Alianza para el Progreso' }, | |
| 'Valderrama': { name: 'Enrique Valderrama', party: 'APRA' }, | |
| } | |
| const SURNAMES = Object.keys(CAND) | |
| const decode = (s) => s | |
| .replace(/<sup[^>]*class="[^"]*reference[^"]*"[^>]*>[\s\S]*?<\/sup>/gi, '') // refs | |
| .replace(/<style[\s\S]*?<\/style>/gi, '') | |
| .replace(/<[^>]+>/g, '') // demais tags | |
| .replace(/&#(\d+);/g, (_, n) => String.fromCharCode(+n)) // entidades numéricas (  espaço, – ndash) | |
| .replace(/ /g, ' ').replace(/–/g, '–').replace(/&/g, '&').replace(/&[a-z]+;/gi, ' ') | |
| .replace(/ /g, ' ') | |
| .replace(/\s+/g, ' ').trim() | |
| // extrai todas as tabelas wikitable | |
| function tables(html) { | |
| const out = [] | |
| const re = /<table[^>]*class="[^"]*wikitable[^"]*"[\s\S]*?<\/table>/gi | |
| let m; while ((m = re.exec(html))) out.push(m[0]) | |
| return out | |
| } | |
| // materializa o grid de uma tabela respeitando rowspan/colspan | |
| function grid(tableHtml) { | |
| const trs = tableHtml.split(/<tr[^>]*>/i).slice(1).map((x) => x.split(/<\/tr>/i)[0]) | |
| const g = []; const pending = [] // {col, span, rows, text} | |
| for (const tr of trs) { | |
| const cells = [] | |
| const cre = /<(t[hd])([^>]*)>([\s\S]*?)<\/\1>/gi | |
| let cm | |
| while ((cm = cre.exec(tr))) { | |
| const attrs = cm[2] | |
| const rs = parseInt((attrs.match(/rowspan="?(\d+)/i) || [])[1] || '1', 10) | |
| const cs = parseInt((attrs.match(/colspan="?(\d+)/i) || [])[1] || '1', 10) | |
| cells.push({ text: decode(cm[3]), rs, cs }) | |
| } | |
| const row = []; let col = 0; let ci = 0 | |
| const place = (text) => { row[col] = text; col++ } | |
| while (ci < cells.length || pending.some((p) => p.rows > 0)) { | |
| const p = pending.find((x) => x.col === col && x.rows > 0) | |
| if (p) { for (let k = 0; k < p.span; k++) place(p.text); p.rows--; continue } | |
| if (ci >= cells.length) break | |
| const c = cells[ci++] | |
| for (let k = 0; k < c.cs; k++) { const cc = col; place(c.text); if (c.rs > 1) pending.push({ col: cc, span: 1, rows: c.rs - 1, text: c.text }) } | |
| } | |
| for (const p of pending) if (p.rows > 0 && p.col >= row.length) { /* trailing spans */ } | |
| g.push(row) | |
| } | |
| return g | |
| } | |
| // rótulo de cada coluna a partir das linhas de cabeçalho | |
| function labelColumns(g) { | |
| const headerRows = g.slice(0, 6) | |
| const ncol = Math.max(...g.map((r) => r.length)) | |
| const labels = [] | |
| for (let c = 0; c < ncol; c++) { | |
| const texts = headerRows.map((r) => r[c] || '') | |
| let label = null | |
| for (const sn of SURNAMES) if (texts.some((t) => t === sn || t.includes(sn))) { label = `cand:${sn}`; break } | |
| if (!label) { | |
| const joined = texts.join(' ').toLowerCase() | |
| if (/pollster/.test(joined)) label = 'pollster' | |
| else if (/sample/.test(joined)) label = 'sample' | |
| else if (/margin/.test(joined)) label = 'margin' | |
| else if (/date/.test(joined)) label = 'date' | |
| else if (/other/.test(joined)) label = 'other' | |
| else if (/blank|none/.test(joined)) label = 'blank' | |
| else if (/undecided/.test(joined)) label = 'undecided' | |
| else if (/lead/.test(joined)) label = 'lead' | |
| } | |
| labels.push(label) | |
| } | |
| return labels | |
| } | |
| const MONTHS = { jan: '01', feb: '02', mar: '03', apr: '04', may: '05', jun: '06', jul: '07', aug: '08', sep: '09', oct: '10', nov: '11', dec: '12' } | |
| // "3–4 Apr 2026" / "28 Feb–5 Mar 2026" / "6 Jun 2026" -> ISO da data FINAL | |
| function endDate(s) { | |
| if (!s) return '' | |
| const last = s.split(/[–-]/).pop().trim() // após o último traço | |
| const ym = s.match(/([A-Za-z]{3})[a-z]*\s+(\d{4})/) // mês+ano do todo (fallback) | |
| let day, mon, year | |
| let mm = last.match(/(\d{1,2})\s+([A-Za-z]{3})[a-z]*\s+(\d{4})/) | |
| if (mm) { day = mm[1]; mon = MONTHS[mm[2].toLowerCase()]; year = mm[3] } | |
| else { const d = last.match(/(\d{1,2})/); day = d ? d[1] : null; mon = ym ? MONTHS[ym[1].toLowerCase()] : null; year = ym ? ym[2] : null } | |
| if (!day || !mon || !year) return '' | |
| return `${year}-${mon}-${String(day).padStart(2, '0')}` | |
| } | |
| const num = (s) => { const m = String(s).replace(/,/g, '').match(/-?\d+(?:\.\d+)?/); return m ? parseFloat(m[0]) : null } | |
| const isData = (txt) => txt && !/^pollster|^date|^sample|^margin|^other|^blank|^lead|results?$/i.test(txt) && txt.length > 1 | |
| // processa todas as tabelas | |
| const frPolls = []; const ruPolls = [] | |
| const allTables = tables(HTML) | |
| allTables.forEach((t, ti) => { | |
| const g = grid(t) | |
| const labels = labelColumns(g) | |
| const candCols = labels.map((l, i) => ({ l, i })).filter((x) => x.l && x.l.startsWith('cand:')) | |
| if (candCols.length < 2) return | |
| const colOf = (name) => labels.indexOf(name) | |
| const pc = colOf('pollster'), dc = colOf('date'), sc = colOf('sample') | |
| if (pc < 0) return | |
| const isRunoff = candCols.length === 2 && candCols.some((x) => x.l === 'cand:Fujimori') && candCols.some((x) => x.l === 'cand:Sánchez') | |
| let kept = 0 | |
| for (const row of g) { | |
| const pollster = row[pc] | |
| if (!isData(pollster)) continue | |
| const date = dc >= 0 ? row[dc] : '' | |
| const iso = endDate(date) | |
| if (process.env.DBG && !isRunoff) console.error(` [#${ti}] "${pollster.slice(0, 18)}" date="${date}" -> ${iso || 'FAIL'}`) | |
| if (!iso) continue // linhas sem data válida (separadores, resultado sem data parseável) são puladas | |
| if (iso < '2026-01-01' || iso > '2026-07-01') continue // só o ciclo 2026 | |
| const sample = sc >= 0 ? num(row[sc]) : null | |
| const results = [] | |
| for (const { l, i } of candCols) { | |
| const sn = l.slice(5); const v = num(row[i]) | |
| if (v != null) results.push({ surname: sn, candidate: CAND[sn].name, party: CAND[sn].party, percent: v }) | |
| } | |
| // 1º turno real lista vários candidatos; eventos/anotações têm 0-1 → exige ≥4 (runoff ≥2) | |
| if (results.length < (isRunoff ? 2 : 4)) continue | |
| if (/death|deadline|withdraw|election|result/i.test(pollster) || /\b(19|20)\d\d\b/.test(pollster)) continue | |
| const rec = { poll_date: iso, fieldwork: date, pollster: pollster.replace(/\s*\(.*/, '').trim(), sample, results } | |
| if (isRunoff) ruPolls.push(rec); else frPolls.push(rec) | |
| kept++ | |
| } | |
| if (kept > 0) console.error(` tabela #${ti}: ${candCols.length} candidatos, ${isRunoff ? 'RUNOFF' : '1º turno'}, ${kept} linhas 2026`) | |
| }) | |
| // dedup por (pollster, poll_date, round) mantendo o mais completo | |
| const dedup = (arr) => { | |
| const m = new Map() | |
| for (const p of arr) { const k = `${p.pollster}|${p.poll_date}`; const prev = m.get(k); if (!prev || p.results.length > prev.results.length) m.set(k, p) } | |
| return [...m.values()].sort((a, b) => a.poll_date.localeCompare(b.poll_date)) | |
| } | |
| const FR = dedup(frPolls); const RU = dedup(ruPolls) | |
| // CSVs long | |
| const frRows = [['poll_date', 'fieldwork', 'pollster', 'sample', 'candidate', 'party', 'percent']] | |
| for (const p of FR) for (const r of p.results) frRows.push([p.poll_date, p.fieldwork, p.pollster, p.sample ?? '', r.candidate, r.party, r.percent]) | |
| writeFileSync(join(OUT, 'peru-first-round-polls.csv'), csv(frRows)) | |
| const ruRows = [['poll_date', 'fieldwork', 'pollster', 'sample', 'fujimori_pct', 'sanchez_pct', 'lead_pp']] | |
| for (const p of RU) { | |
| const f = p.results.find((r) => r.surname === 'Fujimori')?.percent | |
| const s = p.results.find((r) => r.surname === 'Sánchez')?.percent | |
| if (f != null && s != null) ruRows.push([p.poll_date, p.fieldwork, p.pollster, p.sample ?? '', f, s, Math.round((f - s) * 100) / 100]) | |
| } | |
| writeFileSync(join(OUT, 'peru-runoff-polls.csv'), csv(ruRows)) | |
| writeFileSync(join(OUT, 'peru-polls.json'), JSON.stringify({ | |
| description: 'National opinion polls for the 2026 Peruvian general election — all candidates, first round + runoff. Parsed deterministically from the Wikipedia aggregation (rowspan/colspan-aware).', | |
| source: 'Wikipedia "Opinion polling for the 2026 Peruvian general election" (rendered table HTML)', | |
| election: { first_round: '2026-04-12', runoff: '2026-06-07', runoff_matchup: 'Keiko Fujimori (Fuerza Popular) vs Roberto Sánchez (Juntos por el Perú)' }, | |
| counts: { first_round_polls: FR.length, first_round_rows: frRows.length - 1, runoff_polls: RU.length }, | |
| first_round: FR, runoff: RU, | |
| }, null, 2)) | |
| // --- verificação contra valores conhecidos --- | |
| console.log(`1º turno: ${FR.length} pesquisas (${frRows.length - 1} linhas), 2º turno: ${RU.length} pesquisas`) | |
| const cands = new Set(); for (const p of FR) for (const r of p.results) cands.add(r.surname) | |
| console.log(`candidatos distintos no 1º turno: ${cands.size} (${[...cands].join(', ')})`) | |
| const jun6 = RU.find((p) => p.poll_date === '2026-06-06' && /Ipsos/i.test(p.pollster)) | |
| console.log(`CHECK 2T Ipsos 06/Jun (esperado ~Fujimori 44.1 / Sánchez 43.7): ${jun6 ? JSON.stringify(jun6.results.map((r) => [r.surname, r.percent])) : 'NÃO ACHADO'}`) | |
| const apr = FR.filter((p) => p.poll_date.startsWith('2026-04')).slice(-1)[0] | |
| console.log(`CHECK 1T pesquisa mais recente: ${apr ? apr.poll_date + ' ' + apr.pollster + ' ' + JSON.stringify(apr.results.slice(0, 3).map((r) => [r.surname, r.percent])) : 'n/a'}`) | |