andrefelipe-afos
parse-colombia-wiki.mjs: all-equal guard só no 1º turno (runoff pode empatar) + pollster normalization in-parser. Output verified identical (170).
fc31710 | /** | |
| * Parser determinístico das tabelas de pesquisas do artigo Wikipedia "2026 Colombian | |
| * presidential election" (HTML renderizado). Mesma engine do Peru (grid rowspan/colspan-aware). | |
| * 1º turno (todos os candidatos) + 2º turno (de la Espriella × Cepeda). Verifica contra conhecidos. | |
| * | |
| * Entrada: ../../AFOS-Analitica-2026/.cache/col-wiki.html | |
| * Saída: polls/colombia-first-round-polls.csv, polls/colombia-runoff-polls.csv, polls/colombia-polls.json | |
| */ | |
| import { readFileSync, writeFileSync, mkdirSync } from 'fs' | |
| import { join } from 'path' | |
| const HTML = readFileSync(join(process.cwd(), '..', '..', 'AFOS-Analitica-2026', '.cache', 'col-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' | |
| // surname-chave -> {name, party}. 'Espriella' antes de qualquer 'de la' genérico; só 1 Cepeda relevante (Iván). | |
| const CAND = { | |
| 'de la Espriella': { name: 'Abelardo de la Espriella', party: 'Defensores de la Patria' }, | |
| 'Espriella': { name: 'Abelardo de la Espriella', party: 'Defensores de la Patria' }, | |
| 'Cepeda': { name: 'Iván Cepeda', party: 'Pacto Histórico' }, | |
| 'Fajardo': { name: 'Sergio Fajardo', party: 'Dignidad y Compromiso' }, | |
| 'Valencia': { name: 'Paloma Valencia', party: 'Centro Democrático' }, | |
| 'Dávila': { name: 'Vicky Dávila', party: 'Independiente' }, | |
| 'Quintero': { name: 'Daniel Quintero', party: 'Independiente' }, | |
| 'Vargas Lleras': { name: 'Germán Vargas Lleras', party: 'Cambio Radical' }, | |
| 'Galán': { name: 'Juan Manuel Galán', party: 'Nuevo Liberalismo' }, | |
| 'Pizarro': { name: 'María José Pizarro', party: 'Pacto Histórico' }, | |
| 'Pinzón': { name: 'Juan Carlos Pinzón', party: 'Independiente' }, | |
| 'Barreras': { name: 'Roy Barreras', party: 'La Fuerza de la Paz' }, | |
| 'Robledo': { name: 'Jorge Robledo', party: 'Dignidad' }, | |
| 'Lara': { name: 'Rodrigo Lara', party: 'Nuevo Liberalismo' }, | |
| } | |
| const SURNAMES = Object.keys(CAND) | |
| const decode = (s) => s | |
| .replace(/<sup[^>]*class="[^"]*reference[^"]*"[^>]*>[\s\S]*?<\/sup>/gi, '') | |
| .replace(/<style[\s\S]*?<\/style>/gi, '') | |
| .replace(/<[^>]+>/g, '') | |
| .replace(/&#(\d+);/g, (_, n) => String.fromCharCode(+n)) | |
| .replace(/ /g, ' ').replace(/–/g, '–').replace(/&/g, '&').replace(/&[a-z]+;/gi, ' ') | |
| .replace(/\s+/g, ' ').trim() | |
| 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 } | |
| function grid(tableHtml) { | |
| const trs = tableHtml.split(/<tr[^>]*>/i).slice(1).map((x) => x.split(/<\/tr>/i)[0]) | |
| const g = []; const pending = [] | |
| for (const tr of trs) { | |
| const cells = []; const cre = /<(t[hd])([^>]*)>([\s\S]*?)<\/\1>/gi; let cm | |
| while ((cm = cre.exec(tr))) { const a = cm[2]; const rs = parseInt((a.match(/rowspan="?(\d+)/i) || [])[1] || '1', 10); const cs = parseInt((a.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 = (t) => { row[col] = t; 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 }) } | |
| } | |
| g.push(row) | |
| } | |
| return g | |
| } | |
| 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 j = texts.join(' ').toLowerCase() | |
| if (/pollster|firm|polling/.test(j)) label = 'pollster' | |
| else if (/sample/.test(j)) label = 'sample' | |
| else if (/margin/.test(j)) label = 'margin' | |
| else if (/date|fieldwork/.test(j)) label = 'date' | |
| else if (/other/.test(j)) label = 'other' | |
| else if (/blank|none|undecided|absten/.test(j)) label = 'blank' | |
| else if (/lead/.test(j)) 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' } | |
| function endDate(s, fy) { | |
| if (!s) return '' | |
| const last = s.split(/[–-]/).pop().trim(); const ym = s.match(/([A-Za-z]{3})[a-z]*\s+(\d{4})/); let day, mon, year | |
| const 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})/); const monM = last.match(/([A-Za-z]{3})/) || s.match(/([A-Za-z]{3})/) | |
| day = d ? d[1] : null; mon = monM ? MONTHS[monM[1].toLowerCase()] : null; year = ym ? ym[2] : fy | |
| } | |
| 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 = (t) => t && !/^pollster|^date|^sample|^margin|^other|^blank|^lead|results?$/i.test(t) && t.length > 1 | |
| // canonicaliza grafias de instituto (mesmo pollster fragmentado por espaço/grafia) | |
| const normPollster = (p) => p.replace('Atlas Intel/SEMANA', 'AtlasIntel/SEMANA').replace('Noticias RCN /Gad3', 'Noticias RCN/Gad3') | |
| const frPolls = []; const ruPolls = [] | |
| tables(HTML).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:')) | |
| const pc0 = labels.indexOf('pollster'), dc0 = labels.indexOf('date'), sc = labels.indexOf('sample') | |
| if (process.env.DBG) console.error(` [#${ti}] cands=${candCols.length} (${candCols.map((x) => x.l.slice(5)).join('|')}) pollster=${pc0 >= 0} date=${dc0 >= 0} rows=${g.length}`) | |
| if (candCols.length < 2) return | |
| const pc = pc0, dc = dc0 | |
| if (pc < 0) return | |
| const isRunoff = candCols.length === 2 && candCols.some((x) => x.l === 'cand:Cepeda') && candCols.some((x) => x.l.includes('Espriella')) | |
| // ano predominante da tabela (p/ datas sem ano, ex. "13–17 Dec" em seção 2025) | |
| const yc = {}; for (const row of g) { const m = String(row[dc] || '').match(/\b(20\d\d)\b/); if (m) yc[m[1]] = (yc[m[1]] || 0) + 1 } | |
| const tableYear = Object.keys(yc).sort((a, b) => yc[b] - yc[a])[0] || null | |
| let kept = 0 | |
| for (const row of g) { | |
| const pollster = row[pc] | |
| const date = dc >= 0 ? row[dc] : ''; const iso = endDate(date, tableYear) | |
| if (process.env.TBL == ti) console.error(` p="${String(pollster).slice(0, 16)}" date="${date}" iso=${iso || 'X'} isData=${isData(pollster)}`) | |
| if (!isData(pollster)) continue | |
| if (!iso || iso < '2025-01-01' || iso > '2026-07-01') continue | |
| if (pollster.length > 35) continue // pollster real é curto; eventos/contagens têm texto longo | |
| if (/death|deadline|withdraw|election|result|tribunal|count|finali|decision of vote|preliminary|rapid|candidate/i.test(pollster)) continue | |
| if (/\b(19|20)\d\d\b/.test(pollster)) continue | |
| const sample = sc >= 0 ? num(row[sc]) : null | |
| if (sample && sample > 50000) continue // contagem oficial de votos, não pesquisa | |
| const seen = new Set(); const results = [] | |
| for (const { l, i } of candCols) { | |
| const sn = l.slice(5); const nm = CAND[sn].name; if (seen.has(nm)) continue | |
| const v = num(row[i]); if (v != null && v <= 100) { results.push({ candidate: nm, party: CAND[sn].party, percent: v }); seen.add(nm) } | |
| } | |
| if (results.length < (isRunoff ? 2 : 4)) continue | |
| if (!isRunoff && results.every((r) => r.percent === results[0].percent)) continue // 1º turno: todos iguais = artefato (runoff PODE empatar legitimamente) | |
| const rec = { poll_date: iso, fieldwork: date, pollster: normPollster(pollster.replace(/\s*\(.*/, '').trim()), sample, results } | |
| if (isRunoff) ruPolls.push(rec); else frPolls.push(rec); kept++ | |
| } | |
| if (kept) console.error(` tabela #${ti}: ${candCols.length} cands, ${isRunoff ? 'RUNOFF' : '1ºturno'}, ${kept} linhas`) | |
| }) | |
| 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) | |
| 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, 'colombia-first-round-polls.csv'), csv(frRows)) | |
| const ruRows = [['poll_date', 'fieldwork', 'pollster', 'sample', 'espriella_pct', 'cepeda_pct', 'lead_pp']] | |
| for (const p of RU) { const e = p.results.find((r) => r.candidate.includes('Espriella'))?.percent; const c = p.results.find((r) => r.candidate.includes('Cepeda'))?.percent; if (e != null && c != null) ruRows.push([p.poll_date, p.fieldwork, p.pollster, p.sample ?? '', e, c, Math.round((e - c) * 100) / 100]) } | |
| writeFileSync(join(OUT, 'colombia-runoff-polls.csv'), csv(ruRows)) | |
| writeFileSync(join(OUT, 'colombia-polls.json'), JSON.stringify({ | |
| description: 'National opinion polls for the 2026 Colombian presidential election — first round (all candidates) + runoff (de la Espriella vs Cepeda). Parsed deterministically from Wikipedia.', | |
| source: 'Wikipedia "2026 Colombian presidential election" (rendered table HTML) + AS/COA poll tracker', | |
| election: { first_round: '2026-05-31', runoff: '2026-06-21', runoff_matchup: 'Abelardo de la Espriella vs Iván Cepeda' }, | |
| counts: { first_round_polls: FR.length, first_round_rows: frRows.length - 1, runoff_polls: RU.length }, | |
| first_round: FR, runoff: RU, | |
| }, null, 2)) | |
| console.log(`1º turno: ${FR.length} pesquisas (${frRows.length - 1} linhas), 2º turno: ${RU.length}`) | |
| const cands = new Set(); for (const p of FR) for (const r of p.results) cands.add(r.candidate) | |
| console.log(`candidatos 1T: ${cands.size} (${[...cands].join(', ')})`) | |
| console.log(`range 1T: ${FR[0]?.poll_date} → ${FR[FR.length - 1]?.poll_date}`) | |
| if (RU.length) console.log(`runoff amostra: ${JSON.stringify(RU.slice(-2).map((p) => [p.poll_date, p.pollster, p.results.map((r) => [r.candidate.split(' ').pop(), r.percent])]))}`) | |